python_code
stringlengths 0
4.04M
| repo_name
stringlengths 7
58
| file_path
stringlengths 5
147
|
---|---|---|
from meerkat.interactive import Page, print
from meerkat.interactive.app.src.lib.component.core.textbox import Textbox
textbox = Textbox()
print(textbox.text)
page = Page(component=textbox, id="textbox")
page.launch()
| meerkat-main | meerkat/interactive/app/src/lib/component/core/textbox/test_textbox.py |
import meerkat as mk
from meerkat.interactive import Page
from meerkat.interactive.app.src.lib.component.core.stats import Stats
component = mk.gui.html.div(
slots=[
Stats(
data={
"stat_1": 11.34,
"stat_2": 10000.3,
"stat_3": 0.003, # TODO: this displays as 0.00
"stat_4": 10013123.3,
"stat_5": 100131131231.3,
"stat_6": 0.000005, # TODO: this displays as 0.00
},
)
]
)
page = Page(component=component, id="stats")
page.launch()
| meerkat-main | meerkat/interactive/app/src/lib/component/core/stats/test_stats.py |
from typing import Mapping, Union
from meerkat.interactive.app.src.lib.component.abstract import Component
class Stats(Component):
data: Mapping[str, Union[int, float]]
| meerkat-main | meerkat/interactive/app/src/lib/component/core/stats/__init__.py |
from meerkat.interactive.app.src.lib.component.abstract import Component
from meerkat.interactive.endpoint import EndpointProperty
from meerkat.interactive.event import EventInterface
class OnRunEditor(EventInterface):
new_code: str
class Editor(Component):
code: str = ""
title: str = "Code Editor"
on_run: EndpointProperty[OnRunEditor] = None
| meerkat-main | meerkat/interactive/app/src/lib/component/core/editor/__init__.py |
meerkat-main | meerkat/interactive/app/src/lib/component/deprecate/__init__.py |
|
from pydantic import Field
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import EndpointProperty
from meerkat.interactive.graph import Store
from ...abstract import Component
def is_none(x):
return (isinstance(x, Store) and x.__wrapped__ is None) or x is None
class Plot(Component):
# name: str = "Plot"
df: "DataFrame"
x: str
y: str
x_label: str = None
y_label: str = None
type: str = Store("scatter")
slot: str = None
keys_to_remove: list = Field(default_factory=list)
metadata_columns: list = Field(default_factory=list)
on_select: EndpointProperty = None
on_remove: EndpointProperty = None
| meerkat-main | meerkat/interactive/app/src/lib/component/deprecate/plot/__init__.py |
# from typing import List, Union
# import numpy as np
# from meerkat.dataframe import DataFrame
# from meerkat.interactive.app.src.lib.component.abstract import BaseComponent
# from meerkat.interactive.edit import EditTarget
# from meerkat.interactive.graph import Store, make_store
# class Editor(BaseComponent):
# name = "Editor"
# def __init__(
# self,
# df: DataFrame,
# col: Union[Store, str],
# target: EditTarget = None,
# selected: Store[List[int]] = None,
# primary_key: str = None,
# title: str = None,
# ) -> None:
# super().__init__()
# self.col = make_store(col)
# self.text = make_store("")
# self.primary_key = primary_key
# self.df = df
# if target is None:
# df["_edit_id"] = np.arange(len(df))
# target = EditTarget(self.df, "_edit_id", "_edit_id")
# self.target = target
# self.selected = selected
# self.title = title if title is not None else ""
# @property
# def props(self):
# return {
# "df": self.df.config, # FIXME
# "target": self.target.config,
# "col": self.col.config,
# "text": self.text.config,
# "selected": self.selected.config,
# "primary_key": self.primary_key,
# "title": self.title,
# }
| meerkat-main | meerkat/interactive/app/src/lib/component/deprecate/editor/__init__.py |
from typing import List, Optional
from pydantic import validator
from meerkat.interactive.app.src.lib.component.abstract import (
BaseComponent,
Component,
Slottable,
)
from meerkat.tools.utils import classproperty
class HtmlMixin:
@classproperty
def library(cls):
return "html"
@classproperty
def namespace(cls):
return "html"
def _get_ipython_height(self):
import re
# search the classes for the tailwind height class
if isinstance(self.classes, str):
match = re.search(r"(^|\s)h-\[(\d+px)\]", self.classes.value)
if match:
return match.group(2)
return super()._get_ipython_height()
class a(Slottable, HtmlMixin, Component):
classes: Optional[str] = None
style: Optional[str] = None
href: str = ""
target: str = ""
rel: str = ""
class div(Slottable, HtmlMixin, Component):
classes: Optional[str] = None
style: Optional[str] = None
def __init__(
self,
slots: Optional[List[BaseComponent]] = None,
*,
classes: Optional[str] = None,
style: Optional[str] = None,
):
"""A div element.
Args:
slots (List[BaseComponent], optional): The components
to render inside this div. Defaults to None.
classes (str, optional): The Tailwind classes to
apply to this div. Defaults to None.
style (str, optional): The inline CSS to apply to
this div. Defaults to None.
"""
super().__init__(slots=slots, classes=classes, style=style)
class flex(div):
def __init__(
self,
slots: Optional[List[BaseComponent]] = None,
*,
classes: Optional[str] = None,
style: Optional[str] = None,
):
"""A div element with flexbox styling. Places the children in a row.
Args:
slots (List[BaseComponent], optional): The components
to render inside this div. Defaults to None.
classes (str, optional): The Tailwind classes to apply to
this div. Defaults to None.
style (str, optional): The inline CSS to apply to
this div. Defaults to None.
"""
super().__init__(slots=slots, classes=classes, style=style)
@validator("classes", pre=True, always=True)
def make_flex(cls, v):
return "flex flex-row " + v if v is not None else "flex flex-row"
class flexcol(div):
def __init__(
self,
slots: Optional[List[BaseComponent]] = None,
*,
classes: Optional[str] = None,
style: Optional[str] = None,
):
"""A div element with flexbox styling. Places the children in a column.
Args:
slots (List[BaseComponent], optional): The components to
render inside this div. Defaults to None.
classes (str, optional): The Tailwind classes to apply
to this div. Defaults to None.
style (str, optional): The inline CSS to apply to
this div. Defaults to None.
"""
super().__init__(slots=slots, classes=classes, style=style)
@validator("classes", pre=True, always=True)
def make_flexcol(cls, v):
return "flex flex-col " + v if v is not None else "flex flex-col"
class grid(div):
def __init__(
self,
slots: Optional[List[BaseComponent]] = None,
*,
classes: Optional[str] = None,
style: Optional[str] = None,
):
"""A div element with grid styling.
Args:
slots (List[BaseComponent], optional): The components
to render inside this div. Defaults to None.
classes (str, optional): The Tailwind classes to apply
to this div. Defaults to None.
style (str, optional): The inline CSS to apply to this
div. Defaults to None.
"""
super().__init__(slots=slots, classes=classes, style=style)
@validator("classes", pre=True, always=True)
def make_grid(cls, v):
return "grid " + v if v is not None else "grid"
class gridcols2(div):
def __init__(
self,
slots: Optional[List[BaseComponent]] = None,
*,
classes: Optional[str] = None,
style: Optional[str] = None,
):
"""A div element with grid styling and two columns.
Args:
slots (List[BaseComponent], optional): The components to
render inside this div. Defaults to None.
classes (str, optional): The Tailwind classes to apply to
this div. Defaults to None.
style (str, optional): The inline CSS to apply to this div.
Defaults to None.
"""
super().__init__(slots=slots, classes=classes, style=style)
@validator("classes", pre=True, always=True)
def make_gridcols2(cls, v):
return "grid grid-cols-2 " + v if v is not None else "grid grid-cols-2"
class gridcols3(div):
def __init__(
self,
slots: Optional[List[BaseComponent]] = None,
*,
classes: Optional[str] = None,
style: Optional[str] = None,
):
"""A div element with grid styling and three columns.
Args:
slots (List[BaseComponent], optional): The components to
render inside this div. Defaults to None.
classes (str, optional): The Tailwind classes to apply to
this div. Defaults to None.
style (str, optional): The inline CSS to apply to this div.
Defaults to None.
"""
super().__init__(slots=slots, classes=classes, style=style)
@validator("classes", pre=True, always=True)
def make_gridcols3(cls, v):
return "grid grid-cols-3 " + v if v is not None else "grid grid-cols-3"
class gridcols4(div):
def __init__(
self,
slots: Optional[List[BaseComponent]] = None,
*,
classes: Optional[str] = None,
style: Optional[str] = None,
):
"""A div element with grid styling and four columns.
Args:
slots (List[BaseComponent], optional): The components to
render inside this div. Defaults to None.
classes (str, optional): The Tailwind classes to apply to
this div. Defaults to None.
style (str, optional): The inline CSS to apply to this div.
Defaults to None.
"""
super().__init__(slots=slots, classes=classes, style=style)
@validator("classes", pre=True, always=True)
def make_gridcols4(cls, v):
return "grid grid-cols-4 " + v if v is not None else "grid grid-cols-4"
class p(Slottable, HtmlMixin, Component):
classes: Optional[str] = None
style: Optional[str] = None
def __init__(
self,
slots: Optional[List[BaseComponent]] = None,
*,
classes: Optional[str] = None,
style: Optional[str] = None,
):
"""A p element.
Args:
slots (List[BaseComponent], optional): The components to
render inside this div. Defaults to None.
classes (str, optional): The Tailwind classes to apply to
this div. Defaults to None.
style (str, optional): The inline CSS to apply to this div.
Defaults to None.
"""
super().__init__(slots=slots, classes=classes, style=style)
class span(Slottable, HtmlMixin, Component):
classes: Optional[str] = None
style: Optional[str] = None
class h1(Slottable, HtmlMixin, Component):
classes: Optional[str] = "text-4xl"
style: Optional[str] = None
def __init__(
self,
slots: Optional[List[BaseComponent]] = None,
*,
classes: Optional[str] = None,
style: Optional[str] = None,
):
"""An h1 element, with a default font size of 4xl.
Args:
slots (List[BaseComponent], optional): The components to
render inside this div. Defaults to None.
classes (str, optional): The Tailwind classes to apply to
this div. Defaults to None.
style (str, optional): The inline CSS to apply to this div.
Defaults to None.
"""
super().__init__(slots=slots, classes=classes, style=style)
class h2(Slottable, HtmlMixin, Component):
classes: Optional[str] = "text-3xl"
style: Optional[str] = None
def __init__(
self,
slots: Optional[List[BaseComponent]] = None,
*,
classes: Optional[str] = None,
style: Optional[str] = None,
):
"""An h2 element, with a default font size of 3xl.
Args:
slots (List[BaseComponent], optional): The components to
render inside this div. Defaults to None.
classes (str, optional): The Tailwind classes to apply to
this div. Defaults to None.
style (str, optional): The inline CSS to apply to this div.
Defaults to None.
"""
super().__init__(slots=slots, classes=classes, style=style)
class h3(Slottable, HtmlMixin, Component):
classes: Optional[str] = "text-2xl"
style: Optional[str] = None
def __init__(
self,
slots: Optional[List[BaseComponent]] = None,
*,
classes: Optional[str] = None,
style: Optional[str] = None,
):
"""An h3 element, with a default font size of 2xl.
Args:
slots (List[BaseComponent], optional): The components to
render inside this div. Defaults to None.
classes (str, optional): The Tailwind classes to apply to
this div. Defaults to None.
style (str, optional): The inline CSS to apply to this div.
Defaults to None.
"""
super().__init__(slots=slots, classes=classes, style=style)
class h4(Slottable, HtmlMixin, Component):
classes: Optional[str] = "text-xl"
style: Optional[str] = None
def __init__(
self,
slots: Optional[List[BaseComponent]] = None,
*,
classes: Optional[str] = None,
style: Optional[str] = None,
):
"""An h4 element, with a default font size of xl.
Args:
slots (List[BaseComponent], optional): The components to
render inside this div. Defaults to None.
classes (str, optional): The Tailwind classes to apply to
this div. Defaults to None.
style (str, optional): The inline CSS to apply to this div.
Defaults to None.
"""
super().__init__(slots=slots, classes=classes, style=style)
class h5(Slottable, HtmlMixin, Component):
classes: Optional[str] = "text-lg"
style: Optional[str] = None
def __init__(
self,
slots: Optional[List[BaseComponent]] = None,
*,
classes: Optional[str] = None,
style: Optional[str] = None,
):
"""An h5 element, with a default font size of lg.
Args:
slots (List[BaseComponent], optional): The components to
render inside this div. Defaults to None.
classes (str, optional): The Tailwind classes to apply to
this div. Defaults to None.
style (str, optional): The inline CSS to apply to this div.
Defaults to None.
"""
super().__init__(slots=slots, classes=classes, style=style)
class h6(Slottable, HtmlMixin, Component):
classes: Optional[str] = "text-md"
style: Optional[str] = None
def __init__(
self,
slots: Optional[List[BaseComponent]] = None,
*,
classes: Optional[str] = None,
style: Optional[str] = None,
):
"""An h6 element, with a default font size of md.
Args:
slots (List[BaseComponent], optional): The components to
render inside this div. Defaults to None.
classes (str, optional): The Tailwind classes to apply to
this div. Defaults to None.
style (str, optional): The inline CSS to apply to this div.
Defaults to None.
"""
super().__init__(slots=slots, classes=classes, style=style)
# class radio(Slottable, HtmlMixin, Component):
# classes: Optional[str] = None
# style: Optional[str] = None
# name: str = ""
# value: str = ""
# checked: bool = False
# disabled: bool = False
# color: str = "purple"
# on_change: Optional[Endpoint] = None
class svg(Slottable, HtmlMixin, Component):
classes: Optional[str] = None
style: Optional[str] = None
fill: Optional[str] = None
viewBox: Optional[str] = None
stroke: Optional[str] = None
stroke_width: Optional[str] = None
stroke_linecap: Optional[str] = None
stroke_linejoin: Optional[str] = None
# Keeping this attribute in makes the svg component not render
# xmlns: str = "http://www.w3.org/2000/svg"
aria_hidden: Optional[str] = None
class path(Slottable, HtmlMixin, Component):
classes: Optional[str] = None
style: Optional[str] = None
d: Optional[str] = None
fill: Optional[str] = None
clip_rule: Optional[str] = None
fill_rule: Optional[str] = None
stroke: Optional[str] = None
stroke_linecap: Optional[str] = None
stroke_linejoin: Optional[str] = None
stroke_width: Optional[str] = None
class ul(Slottable, HtmlMixin, Component):
classes: Optional[str] = None
style: Optional[str] = None
class ol(Slottable, HtmlMixin, Component):
pass
class li(Slottable, HtmlMixin, Component):
pass
class table(Slottable, HtmlMixin, Component):
pass
class thead(Slottable, HtmlMixin, Component):
pass
class tbody(Slottable, HtmlMixin, Component):
pass
class tr(Slottable, HtmlMixin, Component):
pass
class th(Slottable, HtmlMixin, Component):
pass
class td(Slottable, HtmlMixin, Component):
pass
# class br(HtmlMixin, Component):
# pass
# class hr(HtmlMixin, Component):
# pass
class form(Slottable, HtmlMixin, Component):
classes: Optional[str] = None
style: Optional[str] = None
action: Optional[str] = None
method: str = "get"
enctype: str = "application/x-www-form-urlencoded"
target: Optional[str] = None
class button(Slottable, HtmlMixin, Component):
classes: Optional[str] = None
style: Optional[str] = None
type: str = "button"
value: Optional[str] = None
name: Optional[str] = None
disabled: bool = False
formaction: Optional[str] = None
# class input(Slottable, HtmlMixin, Component):
# pass
# FIXME: remove closing tags in the Wrapper.svelte transipler
# class input(HtmlMixin, Component):
# classes: Optional[str] = None
# style: Optional[str] = None
# type: str = "text"
# value: str = ""
# placeholder: str = ""
# name: str = ""
# class img(Slottable, HtmlMixin, Component):
# src: str = ""
# alt: str = ""
# width: str = ""
# height: str = ""
class textarea(Slottable, HtmlMixin, Component):
pass
class select(Slottable, HtmlMixin, Component):
pass
# class option(Slottable, HtmlMixin, Component):
# pass
# class label(Slottable, HtmlMixin, Component):
# pass
# class form(Slottable, HtmlMixin, Component):
# pass
# class iframe(Slottable, HtmlMixin, Component):
# pass
# class script(Slottable, HtmlMixin, Component):
# pass
# class style(Slottable, HtmlMixin, Component):
# pass
# class link(Slottable, HtmlMixin, Component):
# pass
# class meta(Slottable, HtmlMixin, Component):
# pass
# class header(Slottable, HtmlMixin, Component):
# pass
# class footer(Slottable, HtmlMixin, Component):
# pass
# class nav(Slottable, HtmlMixin, Component):
# pass
# class main(Slottable, HtmlMixin, Component):
# pass
# class section(Slottable, HtmlMixin, Component):
# pass
# class article(Slottable, HtmlMixin, Component):
# pass
# class aside(Slottable, HtmlMixin, Component):
# pass
# class details(Slottable, HtmlMixin, Component):
# pass
# class summary(Slottable, HtmlMixin, Component):
# pass
# class dialog(Slottable, HtmlMixin, Component):
# pass
# class menu(Slottable, HtmlMixin, Component):
# pass
# class menuitem(Slottable, HtmlMixin, Component):
# pass
| meerkat-main | meerkat/interactive/app/src/lib/component/html/__init__.py |
import functools
import os
import pytest
from meerkat.interactive import Page
from meerkat.interactive.app.src.lib.component.html import (
div,
flex,
flexcol,
grid,
gridcols2,
gridcols3,
gridcols4,
h1,
h2,
h3,
h4,
h5,
h6,
)
def hello_div():
return div(slots=["Hello world!"])
def hello_div_k(k=20):
return [hello_div()] * k
def test_div():
return functools.partial(div, slots=hello_div_k())
def test_flex():
return functools.partial(flex, slots=hello_div_k())
def test_flexcol():
return functools.partial(flexcol, slots=hello_div_k())
def test_grid():
return functools.partial(grid, slots=hello_div_k())
def test_gridcols2():
return functools.partial(gridcols2, slots=hello_div_k())
def test_gridcols3():
return functools.partial(gridcols3, slots=hello_div_k())
def test_gridcols4():
return functools.partial(gridcols4, slots=hello_div_k())
@pytest.mark.skipif(os.environ.get("TEST_REMOTE", False), reason="Skip html tests")
def test_html_components():
component = div(
slots=[
"Div with flex-col",
test_div()(classes="flex flex-col bg-slate-200 text-red-800"),
"Div with flex-row",
test_div()(classes="flex flex-row"),
"Div with grid-cols-2",
test_div()(classes="grid grid-cols-2"),
"Flex",
test_flex()(),
"Flexcol",
test_flexcol()(),
"Grid",
test_grid()(),
"Gridcols2",
test_gridcols2()(),
"Gridcols3",
test_gridcols3()(),
"Gridcols4",
test_gridcols4()(),
"H1",
h1(slots=["H1"]),
"H2",
h2(slots=["H2"]),
"H3",
h3(slots=["H3"]),
"H4",
h4(slots=["H4"]),
"H5",
h5(slots=["H5"]),
"H6",
h6(slots=["H6"]),
]
)
page = Page(component=component, id="html")
page.launch()
| meerkat-main | meerkat/interactive/app/src/lib/component/html/test_html.py |
from .area import Area
from .bar import Bar
from .bar_polar import BarPolar
from .box import Box
from .choropleth import Choropleth
from .choropleth_mapbox import ChoroplethMapbox
from .density_contour import DensityContour
from .density_heatmap import DensityHeatmap
from .density_mapbox import DensityMapbox
from .dynamic_scatter import DynamicScatter
from .ecdf import ECDF
from .funnel import Funnel
from .funnel_area import FunnelArea
from .histogram import Histogram
from .icicle import Icicle
from .line import Line
from .line_3d import Line3D
from .line_geo import LineGeo
from .line_mapbox import LineMapbox
from .line_polar import LinePolar
from .line_ternary import LineTernary
from .parallel_categories import ParallelCategories
from .parallel_coordinates import ParallelCoordinates
from .pie import Pie
from .scatter import Scatter
from .scatter_3d import Scatter3D
from .scatter_geo import ScatterGeo
from .scatter_mapbox import ScatterMapbox
from .scatter_matrix import ScatterMatrix
from .scatter_polar import ScatterPolar
from .scatter_ternary import ScatterTernary
from .strip import Strip
from .sunburst import Sunburst
from .timeline import Timeline
from .treemap import Treemap
from .violin import Violin
__all__ = [
"Area",
"Bar",
"BarPolar",
"Box",
"Choropleth",
"ChoroplethMapbox",
"DensityContour",
"DensityHeatmap",
"DensityMapbox",
"DynamicScatter",
"ECDF",
"Funnel",
"FunnelArea",
"Histogram",
"Icicle",
"Line",
"Line3D",
"LineGeo",
"LineMapbox",
"LinePolar",
"LineTernary",
"ParallelCategories",
"ParallelCoordinates",
"Pie",
"Scatter",
"Scatter3D",
"ScatterGeo",
"ScatterMapbox",
"ScatterMatrix",
"ScatterPolar",
"ScatterTernary",
"Strip",
"Sunburst",
"Timeline",
"Treemap",
"Violin",
]
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class ScatterMapbox(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
lat=None,
lon=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.scatter_mapbox.html for more
details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.scatter_mapbox(df.to_pandas(), lat=lat, lon=lon, color=color, **kwargs)
super().__init__(
df=df,
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/scatter_mapbox/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class ParallelCategories(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
dimensions=None,
labels=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.parallel_categories.html for more
details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.parallel_categories(
df.to_pandas(),
dimensions=dimensions,
labels=labels,
**kwargs,
)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/parallel_categories/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class Scatter3D(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
x=None,
y=None,
z=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.scatter_3d.html for more details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.scatter_3d(df.to_pandas(), x=x, y=y, z=z, color=color, **kwargs)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/scatter_3d/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class Violin(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
x=None,
y=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.violin.html for more details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.violin(df.to_pandas(), x=x, y=y, color=color, **kwargs)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/violin/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class ScatterMatrix(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
dimensions=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.scatter_matrix.html for more
details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.scatter_matrix(
df.to_pandas(),
dimensions=dimensions,
color=color,
**kwargs,
)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/scatter_matrix/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class Box(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
x=None,
y=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.box.html for more details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.box(df.to_pandas(), x=x, y=y, color=color, **kwargs)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/box/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class Strip(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
x=None,
y=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.strip.html for more details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.strip(df.to_pandas(), x=x, y=y, color=color, **kwargs)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/strip/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class ScatterGeo(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
lat=None,
lon=None,
locations=None,
locationmode=None,
geojson=None,
featureidkey=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.scatter_geo.html for more
details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.scatter_geo(
df.to_pandas(),
lat=lat,
lon=lon,
locations=locations,
locationmode=locationmode,
geojson=geojson,
featureidkey=featureidkey,
color=color,
**kwargs,
)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/scatter_geo/__init__.py |
from meerkat.tools.utils import classproperty
from ...abstract import Component
class Plot(Component):
title: str
@classproperty
def namespace(cls):
return "plotly"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/plot/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class Area(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
x=None,
y=None,
line_group=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.area.html for more details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.area(
df.to_pandas(),
x=x,
y=y,
line_group=line_group,
color=color,
**kwargs,
)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/area/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class LineMapbox(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
lat=None,
lon=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.line_mapbox.html for more
details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.line_mapbox(
df.to_pandas(),
lat=lat,
lon=lon,
color=color,
**kwargs,
)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/line_mapbox/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class LineGeo(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
lat=None,
lon=None,
locations=None,
locationmode=None,
geojson=None,
featureidkey=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.line_geo.html for more details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.line_geo(
df.to_pandas(),
lat=lat,
lon=lon,
locations=locations,
locationmode=locationmode,
geojson=geojson,
featureidkey=featureidkey,
color=color,
**kwargs,
)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/line_geo/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class DensityContour(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
x=None,
y=None,
z=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.density_contour.html for more
details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.density_contour(
df.to_pandas(),
x=x,
y=y,
z=z,
color=color,
**kwargs,
)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/density_contour/__init__.py |
import json
from typing import List
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.ibis import IbisDataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty, endpoint
from meerkat.interactive.event import EventInterface
from meerkat.interactive.graph import Store, reactive
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
ibis = LazyLoader("ibis")
class OnRelayoutInterface(EventInterface):
"""Defines the interface for an event.
Subclass this to define the interface for a new event type.
The class will specify the keyword arguments returned by an event from the
frontend to any endpoint that has subscribed to it.
All endpoints that are expected to receive an event of this type should
ensure they have a signature that matches the keyword arguments defined
in this class.
"""
x_range: List[float]
y_range: List[float]
class DynamicScatter(Component):
df: DataFrame
on_click: EndpointProperty = None
on_relayout: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
data: str = ""
layout: str = ""
filtered_df: DataFrame = None
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
x=None,
y=None,
color=None,
max_points: int = 1_000,
on_click: EndpointProperty = None,
on_relayout: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.scatter.html for more details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
full_size = len(df) # noqa: F841
@reactive()
def get_layout(df: DataFrame, x: str, y: str, color: str):
if isinstance(df, IbisDataFrame):
fig_df = DataFrame.from_pandas(
df.expr.order_by(ibis.random())
.limit(max_points)[x, y, color]
.execute()
)
else:
fig_df = df if len(df) <= max_points else df.sample(max_points)
fig = px.scatter(fig_df.to_pandas(), x=x, y=y, color=color, **kwargs)
return json.dumps(json.loads(fig.to_json())["layout"])
layout = get_layout(df, x=x, y=y, color=color)
axis_range = Store({"x0": None, "x1": None, "y0": None, "y1": None})
@endpoint()
def on_relayout(axis_range: Store[dict], x_range, y_range):
axis_range.set(
{"x0": x_range[0], "x1": x_range[1], "y0": y_range[0], "y1": y_range[1]}
)
@reactive()
def filter_df(df: DataFrame, axis_range: dict, x: str, y: str):
is_ibis = isinstance(df, IbisDataFrame)
if is_ibis:
df = df.expr
else:
df = df.view()
if axis_range["x0"] is not None:
df = df[axis_range["x0"] < df[x]]
if axis_range["x1"] is not None:
df = df[df[x] < axis_range["x1"]]
if axis_range["y0"] is not None:
df = df[axis_range["y0"] < df[y]]
if axis_range["y1"] is not None:
df = df[df[y] < axis_range["y1"]]
if is_ibis:
df = IbisDataFrame(df)
return df
@reactive()
def sample_df(df: DataFrame):
is_ibis = isinstance(df, IbisDataFrame)
if is_ibis:
df = DataFrame.from_pandas(
df.expr.order_by(ibis.random())
.limit(max_points)[x, y, color, df.primary_key_name]
.execute()
)
else:
df = df.view()
if len(df) > max_points:
df = df.sample(max_points)
return df
@reactive()
def compute_plotly(df: DataFrame, x: str, y: str, color: str):
fig = px.scatter(df.to_pandas(), x=x, y=y, color=color, **kwargs)
return json.dumps(json.loads(fig.to_json())["data"])
df.mark()
filtered_df = filter_df(df=df, axis_range=axis_range, x=x, y=y)
sampled_df = sample_df(df=filtered_df)
plotly_data = compute_plotly(df=sampled_df, x=x, y=y, color=color)
super().__init__(
df=df,
on_click=on_click,
selected=selected,
on_select=on_select,
on_relayout=on_relayout.partial(axis_range=axis_range),
data=plotly_data,
layout=layout,
filtered_df=filtered_df,
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/dynamic_scatter/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class DensityMapbox(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
lat=None,
lon=None,
z=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.density_mapbox.html for more
details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.density_mapbox(df.to_pandas(), lat=lat, lon=lon, z=z, **kwargs)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/density_mapbox/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class FunnelArea(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
names=None,
values=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.funnel_area.html for more
details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.funnel_area(
df.to_pandas(),
names=names,
values=values,
color=color,
**kwargs,
)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/funnel_area/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class BarPolar(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
r=None,
theta=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.bar_polar.html for more details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.bar_polar(
df.to_pandas(),
r=r,
theta=theta,
color=color,
**kwargs,
)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/bar_polar/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class ParallelCoordinates(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
dimensions=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.parallel_categories.html for more
details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.parallel_categories(
df.to_pandas(),
dimensions=dimensions,
color=color,
**kwargs,
)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/parallel_coordinates/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class Pie(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
names=None,
values=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.pie.html for more details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.pie(
df.to_pandas(),
names=names,
values=values,
color=color,
**kwargs,
)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/pie/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class Choropleth(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
lat=None,
lon=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.choropleth.html for more details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.choropleth(
df.to_pandas(),
lat=lat,
lon=lon,
color=color,
**kwargs,
)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/choropleth/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class Scatter(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
x=None,
y=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.scatter.html for more details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.scatter(df.to_pandas(), x=x, y=y, color=color, **kwargs)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/scatter/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class Line(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
x=None,
y=None,
line_group=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.line.html for more details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.line(
df.to_pandas(),
x=x,
y=y,
line_group=line_group,
color=color,
**kwargs,
)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/line/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class LinePolar(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
r=None,
theta=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.line_polar.html for more details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.line_polar(df.to_pandas(), r=r, theta=theta, color=color, **kwargs)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/line_polar/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class ScatterTernary(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
a=None,
b=None,
c=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.scatter_ternary.html for more
details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.scatter_ternary(df.to_pandas(), a=a, b=b, c=c, color=color, **kwargs)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/scatter_ternary/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class ECDF(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
x=None,
y=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.ecdf.html for more details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.ecdf(df.to_pandas(), x=x, y=y, color=color, **kwargs)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/ecdf/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class Icicle(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
names=None,
values=None,
parents=None,
path=None,
ids=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.icicle.html for more details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.icicle(
df.to_pandas(),
names=names,
values=values,
parents=parents,
path=path,
ids=ids,
color=color,
**kwargs,
)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/icicle/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class ChoroplethMapbox(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
geojson=None,
featureidkey=None,
locations=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.choropleth_mapbox.html for more
details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.choropleth_mapbox(
df.to_pandas(),
geojson=geojson,
featureidkey=featureidkey,
locations=locations,
color=color,
**kwargs,
)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/choropleth_mapbox/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class DensityHeatmap(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
x=None,
y=None,
z=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.density_heatmap.html for more
details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.density_heatmap(df.to_pandas(), x=x, y=y, z=z, **kwargs)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/density_heatmap/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class Bar(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
x=None,
y=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.scatter_mapbox.html for more
details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
if len(df[x].unique()) != len(df):
df = df.groupby(x)[[x, y]].mean()
df.create_primary_key("id")
fig = px.bar(df.to_pandas(), x=x, y=y, color=color, **kwargs)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/bar/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class Timeline(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
x_start=None,
x_end=None,
y=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.timeline.html for more details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.timeline(
df.to_pandas(),
x_start=x_start,
x_end=x_end,
y=y,
color=color,
**kwargs,
)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/timeline/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class Sunburst(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
names=None,
values=None,
parents=None,
path=None,
ids=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.sunburst.html for more details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.sunburst(
df.to_pandas(),
names=names,
values=values,
parents=parents,
path=path,
ids=ids,
color=color,
**kwargs,
)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/sunburst/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class ScatterPolar(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
r=None,
theta=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.scatter_polar.html for more
details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.scatter_polar(df.to_pandas(), r=r, theta=theta, color=color, **kwargs)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/scatter_polar/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class Line3D(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
x=None,
y=None,
z=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.line_3d.html for more details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.line_3d(df.to_pandas(), x=x, y=y, z=z, color=color, **kwargs)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/line_3d/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class Funnel(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
x=None,
y=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.funnel.html for more details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.funnel(df.to_pandas(), x=x, y=y, color=color, **kwargs)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/funnel/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class Treemap(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
names=None,
values=None,
parents=None,
ids=None,
path=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.treemap.html for more details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.treemap(
df.to_pandas(),
names=names,
values=values,
parents=parents,
ids=ids,
path=path,
color=color,
**kwargs,
)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/treemap/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class LineTernary(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
a=None,
b=None,
c=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.line_ternary.html for more
details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.line_ternary(df.to_pandas(), a=a, b=b, c=c, color=color, **kwargs)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/line_ternary/__init__.py |
from typing import List, Union
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, EndpointProperty
from meerkat.tools.lazy_loader import LazyLoader
from meerkat.tools.utils import classproperty, requires
from ...abstract import Component
px = LazyLoader("plotly.express")
class Histogram(Component):
df: DataFrame
keyidxs: List[Union[str, int]]
on_click: EndpointProperty = None
selected: List[str] = []
on_select: Endpoint = None
json_desc: str = ""
@requires("plotly.express")
def __init__(
self,
df: DataFrame,
*,
x=None,
y=None,
color=None,
on_click: EndpointProperty = None,
selected: List[str] = [],
on_select: Endpoint = None,
**kwargs,
):
"""See https://plotly.com/python-api-
reference/generated/plotly.express.histogram.html for more details."""
if not env.is_package_installed("plotly"):
raise ValueError(
"Plotly components require plotly. Install with `pip install plotly`."
)
if df.primary_key_name is None:
raise ValueError("Dataframe must have a primary key")
fig = px.histogram(df.to_pandas(), x=x, y=y, color=color, **kwargs)
super().__init__(
df=df,
keyidxs=df.primary_key.values.tolist(),
on_click=on_click,
selected=selected,
on_select=on_select,
json_desc=fig.to_json(),
)
@classproperty
def namespace(cls):
return "plotly"
def _get_ipython_height(self):
return "800px"
| meerkat-main | meerkat/interactive/app/src/lib/component/plotly/histogram/__init__.py |
from .flash_fill import FlashFill
from .gallery_query import GalleryQuery
__all__ = ["FlashFill", "GalleryQuery"]
| meerkat-main | meerkat/interactive/app/src/lib/component/contrib/__init__.py |
# from typing import Any, Dict, List, Optional, Sequence, Union
# import numpy as np
# import pandas as pd
# from pydantic import BaseModel, Field
# from meerkat.columns.abstract import Column
# from meerkat.columns.scalar import ScalarColumn
# from meerkat.dataframe import DataFrame
# from meerkat.interactive.endpoint import Endpoint, endpoint
# from meerkat.interactive.graph import Store, react
# from ..abstract import BaseComponent
# @react()
# def run_formula_bar(df: DataFrame, code: str):
# df = df.view() # this is needed to avoid cycles in simple df case
# lines = code.split("\n")
# _locals = locals()
# exec("\n".join(lines[:-1]), {}, _locals)
# return eval(lines[-1], {}, _locals)
# @endpoint
# def on_run(code: Store[str], new_code: str):
# print("is endpoint running")
# code.set(new_code)
# return code
# class FormulaBar(BaseComponent):
# on_run: Endpoint = None
# def __init__(self, **kwargs):
# super().__init__(**kwargs)
# self.code = Store("df", backend_only=True)
# self.on_run = on_run.partial(code=self.code)
# def __call__(self, df: DataFrame):
# out = run_formula_bar(df, self.code)
# if not isinstance(out, DataFrame):
# raise ValueError("The code must return a DataFrame.")
# return out
| meerkat-main | meerkat/interactive/app/src/lib/component/contrib/formula_bar/__init__.py |
from typing import TYPE_CHECKING
from meerkat.interactive.app.src.lib.component.core.carousel import Carousel
from meerkat.interactive.app.src.lib.component.core.gallery import Gallery
from meerkat.interactive.app.src.lib.component.core.markdown import Caption
from meerkat.interactive.app.src.lib.component.core.match import Match
from meerkat.interactive.graph.magic import magic
from meerkat.interactive.graph.reactivity import reactive
from meerkat.ops.cond import _bool as mkbool
from meerkat.ops.cond import cor
from ...html import div, flex, flexcol
if TYPE_CHECKING:
from meerkat import DataFrame
class GalleryQuery(div):
# match: Match = None
# gallery: Gallery = None
def __init__(
self,
df: "DataFrame",
main_column: str,
against: str,
allow_selection: bool = False,
classes: str = "h-screen",
):
"""
Args:
df: The DataFrame to match against and select examples from.
main_column: The main column to display in the gallery.
against: The column to match against.
allow_selection: Whether to allow the user to select examples
from the gallery even when not in image match mode.
Note the selection will be reset when the user switches
to a different mode.
classes: The classes to apply to the div.
"""
from meerkat.ops.sort import sort
match = Match(
df=df,
against=against,
)
df = df.mark()
# Get the name of the match criterion in a reactive way.
with magic():
criterion_name = match.criterion.name
# Sort
df_sorted = sort(data=df, by=criterion_name, ascending=False)
# Gallery
with magic():
allow_selection = cor(allow_selection, mkbool(match._mode))
gallery = Gallery(
df_sorted,
main_column=main_column,
allow_selection=allow_selection,
)
match.set_selection(gallery.selected)
@reactive()
def get_positives(df, positive_selection, _positive_selection, selection, mode):
if mode == "set_positive_selection":
selected = positive_selection
else:
selected = _positive_selection
if selected:
return df.loc[selected]
else:
return df.head(0)
@reactive()
def get_negatives(df, negative_selection, _negative_selection, selection, mode):
if mode == "set_negative_selection":
selected = negative_selection
else:
selected = _negative_selection
if selected:
return df.loc[selected]
else:
return df.head(0)
positive_caption_classes = reactive(
lambda mode: "text-sm self-center mb-1"
if mode == "set_positive_selection"
else "text-sm self-center mb-1 text-gray-400"
)
negative_caption_classes = reactive(
lambda mode: "text-sm self-center mb-1"
if mode == "set_negative_selection"
else "text-sm self-center mb-1 text-gray-400"
)
carousel_positives = Carousel(
get_positives(
df,
match.positive_selection,
match._positive_selection,
gallery.selected,
match._mode,
),
main_column=main_column,
)
carousel_negatives = Carousel(
get_negatives(
df,
match.negative_selection,
match._negative_selection,
gallery.selected,
match._mode,
),
main_column=main_column,
)
df.unmark()
component = div(
[
match,
flex(
[
flexcol(
[
Caption(
"Negative Query Images Selected",
classes=negative_caption_classes(match._mode),
),
carousel_negatives,
],
classes="flex-1 justify-center align-middle",
),
flexcol(
[
Caption(
"Positive Query Images Selected",
classes=positive_caption_classes(match._mode),
),
carousel_positives,
],
classes="flex-1 justify-center align-middle",
),
],
classes="justify-center gap-4 my-2",
),
gallery,
],
classes="h-full grid grid-rows-[auto,auto,4fr]",
)
super().__init__(
slots=[component],
classes=classes,
)
self.match = match
self.gallery = gallery
def _get_ipython_height(self) -> str:
return "1000px"
| meerkat-main | meerkat/interactive/app/src/lib/component/contrib/gallery_query/__init__.py |
import os
from typing import TYPE_CHECKING, List
import numpy as np
from meerkat.interactive.app.src.lib.component.contrib.discover import Discover
from meerkat.interactive.app.src.lib.component.contrib.global_stats import GlobalStats
from meerkat.interactive.app.src.lib.component.contrib.row import Row
from meerkat.interactive.app.src.lib.component.core.filter import FilterCriterion
from meerkat.interactive.app.src.lib.component.deprecate.plot import Plot
from meerkat.ops.sliceby.sliceby import SliceBy
from meerkat.tools.lazy_loader import LazyLoader
from ...abstract import BaseComponent
if TYPE_CHECKING:
from meerkat.dataframe import DataFrame
manifest = LazyLoader("manifest")
DELTA_COLUMN = "delta"
class ChangeList(BaseComponent):
code_control: bool = False
gallery: BaseComponent
gallery_match: BaseComponent
gallery_filter: BaseComponent
gallery_sort: BaseComponent
gallery_fm_filter: BaseComponent
gallery_code: BaseComponent
discover: BaseComponent
plot: BaseComponent
active_slice: BaseComponent
slice_sort: BaseComponent
slice_match: BaseComponent
global_stats: BaseComponent
metric: str = ("Accuracy",)
v1_name: str = (None,)
v2_name: str = (None,)
def __init__(
self,
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,
):
from mocha.repo import SliceRepo
import meerkat as mk
v1_name = v1_name or v1_column
v2_name = v2_name or v2_column
if tag_columns is None:
tag_columns = []
if df.primary_key is None:
raise ValueError("The DataFrame must have a primary key set.")
df[DELTA_COLUMN] = df[v2_column] - df[v1_column]
if os.path.exists(os.path.join(repo_path, "membership.mk")):
slice_repo = SliceRepo.read(repo_path)
else:
slice_repo = SliceRepo(df, repo_path)
membership_df = slice_repo.membership
slices_df = slice_repo.slices
base_examples = df
with mk.gui.reactive():
examples_df = mk.merge(base_examples, membership_df, on=df.primary_key_name)
examples_df = mk.sample(examples_df, len(examples_df))
# SLICE OVERVIEW
@mk.gui.reactive
def compute_slice_scores(examples: mk.DataPanel, slices: mk.DataPanel):
"""Produce a DataFrame with average delta's (and counts) for
each slice."""
sb = examples.sliceby(
slices["slice_id"].apply(slice_repo._slice_column)
)
result = sb[DELTA_COLUMN].mean()
# compute prototype image embeddings
image_prototypes_df = sb[[embed_column]].mean(axis=0)
image_prototypes_df["slice_id"] = image_prototypes_df["slice"].map(
slice_repo._slice_id
)
image_prototypes_df.remove_column("slice")
slices = slices.merge(image_prototypes_df, on="slice_id")
# # Hacky way to rename DELTA_COLUMN column -> count
count = sb[DELTA_COLUMN].count()
count["count"] = count[DELTA_COLUMN]
count = count[["slice", "count"]]
result = result.merge(count, on="slice")
result = result.sort(by=DELTA_COLUMN, ascending=False)
slices["slice"] = slices["slice_id"].apply(slice_repo._slice_column)
out = (
slices[
"slice_id",
"name",
"description",
"slice",
embed_column,
]
.merge(result, on="slice")
.drop("slice")
)
slices.remove_column("slice")
return out
stats_df = compute_slice_scores(examples=examples_df, slices=slices_df)
@mk.endpoint()
def append_to_sort(match_criterion, criteria: mk.Store):
SOURCE = "match"
criterion = mk.gui.Sort.create_criterion(
column=match_criterion.name, ascending=False, source=SOURCE
)
criteria.set([criterion] + [c for c in criteria if c.source != SOURCE])
sort_criteria = mk.Store([])
match = mk.gui.Match(
df=base_examples,
against=embed_column,
title="Search Examples",
on_match=append_to_sort.partial(criteria=sort_criteria),
)
examples_df, _ = match(examples_df)
# sort the gallery
sort = mk.gui.Sort(
df=examples_df, criteria=sort_criteria, title="Sort Examples"
)
# the filter for the gallery
# TODO(sabri): make this default to the active slice
filter = mk.gui.Filter(df=examples_df, title="Filter Examples")
fm_filter = mk.gui.FMFilter(
df=examples_df,
manifest_session=manifest.Manifest(
client_name="huggingface",
client_connection="http://127.0.0.1:7861",
temperature=0.1,
),
)
code = mk.gui.CodeCell()
current_examples = filter(examples_df)
current_examples = code(current_examples)
current_examples = fm_filter(current_examples)
current_examples = sort(current_examples)
# removing dirty entries does not use the returned criteria.
# but we need to pass it as an argument so that the topological sort
# runs this command after the match.
slice_sort = mk.gui.Sort(df=stats_df, criteria=[], title="Sort Slices")
sb_match = mk.gui.Match(
df=stats_df,
against=embed_column,
title="Search Slices",
on_match=append_to_sort.partial(criteria=slice_sort.criteria),
)
stats_df, _ = sb_match()
stats_df = slice_sort(stats_df)
@mk.endpoint()
def on_select_slice(
slice_id: str,
criteria: mk.Store,
code: str,
query: str,
):
"""Update the gallery filter criteria with the selected slice.
The gallery should be filtered based on the selected
slice. If no slice is selected, there shouldn't be any
filtering based on the slice. When the selected slice is
changed, we should replace the existing filter criteria
with the new one.
"""
source = "on_select_slice"
# wrapped = [
# x if isinstance(x, FilterCriterion) else FilterCriterion(**x)
# for x in criteria
# ]
# on_select_criterion = [x for x in wrapped if x.source == source]
# assert (
# len(on_select_criterion) <= 1
# ), "Something went wrong - Cannot have more than one selected slice"
# for x in on_select_criterion:
# wrapped.remove(x)
wrapped = []
if slice_id:
wrapped.append(
FilterCriterion(
is_enabled=True,
column=slice_repo._slice_column(slice_id),
op="==",
value=True,
source=source,
)
)
code.set("df")
query.set("__default__")
criteria.set(wrapped)
# set to empty string if None
# TODO: Need mk.None
# selected.set(slice_id or "")
@mk.endpoint()
def on_remove(slice_id: str, slices_df: mk.DataFrame):
slice_repo.remove(slice_id)
mod = mk.gui.DataFrameModification(
id=slices_df.id, scope=slices_df.columns
)
mod.add_to_queue()
slice_repo.write()
@mk.gui.reactive
def get_selected_slice_id(
criteria: List[FilterCriterion],
code: str,
query: str,
):
if len(criteria) == 1 and query == "__default__" and code == "df":
criterion = criteria[0]
if criterion.source == "on_select_slice":
return slice_repo._slice_id(criterion.column)
return ""
selected_slice_id = get_selected_slice_id(
filter.criteria, code.code, fm_filter.query
)
plot = Plot(
df=stats_df,
x=DELTA_COLUMN,
y="name",
x_label="Accuracy Shift",
y_label="slice",
metadata_columns=["count", "description"],
on_select=on_select_slice.partial(
criteria=filter.criteria, query=fm_filter.query, code=code.code
),
on_remove=on_remove.partial(slices_df=slices_df),
)
@mk.endpoint()
def on_write_row(key: str, column: str, value: str, df: mk.DataFrame):
"""Change the value of a column in the slice_df."""
if not key:
return
df[column][df.primary_key._keyidx_to_posidx(key)] = value
# We have to force add the dataframe modification to trigger
# downstream updates
mod = mk.gui.DataFrameModification(id=df.id, scope=[column])
mod.add_to_queue()
slice_repo.write()
@mk.gui.reactive
def compute_stats(df: mk.DataFrame):
return {
"count": len(df),
f"{metric} Shift": df[DELTA_COLUMN].mean(),
f"v1 {metric}": df[v1_column].mean(),
f"v2 {metric}": df[v2_column].mean(),
}
stats = compute_stats(current_examples)
@mk.endpoint()
def on_slice_creation(examples_df: mk.DataFrame):
current_df = filter(examples_df)
current_df = code(current_df)
current_df = fm_filter(current_df)
slice_id = slice_repo.add(
name="Unnamed Slice",
membership=mk.DataFrame(
{
current_df.primary_key_name: current_df.primary_key,
"slice": np.ones(len(current_df)),
},
primary_key=current_df.primary_key_name,
),
)
slice_repo.write()
return slice_id
active_slice_view = Row(
df=stats_df,
selected_key=selected_slice_id,
columns=["name", "description"],
stats=stats,
# rename={""}
title="Active Slice",
on_change=on_write_row.partial(
df=slices_df
), # the edits should be written on the slices_df
on_slice_creation=on_slice_creation.partial(
examples_df=examples_df
).compose(
on_select_slice.partial(
criteria=filter.criteria,
query=fm_filter.query,
code=code.code,
)
),
)
@mk.gui.reactive
def subselect_columns(df):
return df[
list(
set(
[
main_column,
DELTA_COLUMN,
label_column,
v1_column,
v2_column,
current_examples.primary_key_name,
]
+ tag_columns
)
)
]
gallery = mk.gui.Gallery(
df=subselect_columns(current_examples),
main_column=main_column,
tag_columns=tag_columns,
)
@mk.endpoint()
def add_discovered_slices(eb: SliceBy):
for key, slice in eb.slices.items():
col = np.zeros(len(slice_repo.membership))
col[slice] = 1
# FIXME: make this interface less awful
slice_repo.add(
name=f"discovered_{key}",
membership=mk.DataFrame(
{
eb.data.primary_key_name: eb.data.primary_key,
"slice": col,
},
primary_key=eb.data.primary_key_name,
),
)
# add a sort by created time
discover = Discover(
df=examples_df,
by=embed_column,
target=v1_column,
pred=v2_column,
on_discover=add_discovered_slices,
)
stats = GlobalStats(
v1_name=v1_name,
v2_name=v2_name,
v1_mean=examples_df[v1_column].mean(),
v2_mean=examples_df[v2_column].mean(),
shift=examples_df[DELTA_COLUMN].mean(),
inconsistency=examples_df[DELTA_COLUMN].std(),
metric=metric,
)
super().__init__(
gallery_match=match,
gallery_filter=filter,
gallery_sort=sort,
gallery_fm_filter=fm_filter,
gallery_code=code,
gallery=gallery,
discover=discover,
global_stats=stats,
active_slice=active_slice_view,
plot=plot,
slice_sort=slice_sort,
slice_match=sb_match,
v1_name=v1_name,
v2_name=v2_name,
metric=metric,
code_control=code_control,
)
| meerkat-main | meerkat/interactive/app/src/lib/component/contrib/mocha/__init__.py |
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import EndpointProperty, endpoint
from ...abstract import Component
@endpoint
def get_discover_schema(df: DataFrame):
import meerkat as mk
from meerkat.interactive.api.routers.dataframe import (
SchemaResponse,
_get_column_infos,
)
columns = [
k
for k, v in df.items()
if isinstance(v, mk.TorchTensorColumn) and len(v.shape) == 2
]
return SchemaResponse(
id=df.id,
columns=_get_column_infos(df, columns),
nrows=len(df),
)
@endpoint
def discover(df: DataFrame, by: str, target: str, pred: str):
eb = df.explainby(
by,
target={"targets": target, "pred_probs": pred},
n_slices=10,
n_mixture_components=10,
n_pca_components=256,
use_cache=False,
)
return eb
class Discover(Component):
df: DataFrame
by: str
target: str = None
pred: str = None
on_discover: EndpointProperty = None
get_discover_schema: EndpointProperty = None
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.get_discover_schema = get_discover_schema.partial(
df=self.df,
)
on_discover = discover.partial(df=self.df, target=self.target, pred=self.pred)
if self.on_discover is not None:
on_discover = on_discover.compose(self.on_discover)
self.on_discover = on_discover
| meerkat-main | meerkat/interactive/app/src/lib/component/contrib/discover/__init__.py |
# from typing import List, Union
# from meerkat.dataframe import DataFrame
# from meerkat.interactive.edit import EditTarget
# from meerkat.interactive.graph import Store, make_store
# from ..abstract import BaseComponent
# class StatsLabeler(BaseComponent):
# name = "StatsLabeler"
# def __init__(
# self,
# df: DataFrame,
# label_target: EditTarget = None,
# phase_target: EditTarget = None,
# phase: Union[Store[str], str] = "train",
# active_key: Union[Store[str], str] = None,
# selected: Store[List[int]] = None,
# primary_key: str = None,
# precision_estimate: List[Store[float]] = None,
# recall_estimate: List[Store[float]] = None,
# ) -> None:
# super().__init__()
# self.df = df
# self.label_target = label_target
# self.phase_target = phase_target
# self.phase = make_store(phase)
# self.active_key = make_store(active_key)
# self.selected = make_store(selected)
# self.primary_key = primary_key
# self.precision_estimate = make_store(precision_estimate)
# self.recall_estimate = make_store(recall_estimate)
# @property
# def props(self):
# return {
# "df": self.df.config, # FIXME
# "label_target": self.label_target.config,
# "phase_target": self.phase_target.config,
# "phase": self.phase.config,
# "active_key": self.active_key.config,
# "selected": self.selected.config,
# "primary_key": self.primary_key,
# "precision_estimate": self.precision_estimate.config,
# "recall_estimate": self.recall_estimate.config,
# }
| meerkat-main | meerkat/interactive/app/src/lib/component/contrib/stats_labeler/__init__.py |
# from meerkat.dataframe import DataFrame
# from ..abstract import BaseComponent
# class SchemaTree(BaseComponent):
# name = "SchemaTree"
# def __init__(
# self,
# df: DataFrame,
# ) -> None:
# super().__init__()
# self.df = df
# @property
# def props(self):
# return {
# "df": self.df.config, # FIXME
# }
| meerkat-main | meerkat/interactive/app/src/lib/component/contrib/lm/__init__.py |
import os
import re
from functools import partial
from typing import TYPE_CHECKING, Dict
from ...html import div
if TYPE_CHECKING:
from meerkat import Component, DataFrame
class FlashFill(div):
"""A component for flash filling a column of data using large language
models.
Args:
df (DataFrame): The dataframe to flash fill.
target_column (str): The column to flash fill.
"""
def __init__(
self,
df: "DataFrame",
target_column: str,
manifest_cache_dir: str = "~/.cache/manifest",
max_tokens: int = 1,
):
df = df.view()
if target_column not in df.columns:
df[target_column] = ""
df["is_train"] = False
component, prompt = self._build_component(df)
super().__init__(
slots=[component],
classes="h-full w-full",
)
self._prompt = prompt
self.manifest_cache_dir = os.path.abspath(
os.path.expanduser(manifest_cache_dir)
)
os.makedirs(self.manifest_cache_dir, exist_ok=True)
self.max_tokens = max_tokens
@property
def prompt(self):
pattern = r"^((.|\n)*)\{([^}]+)\}$"
# Use re.search to find the match in the example_template string
match = re.search(pattern, self._prompt.value)
return match.group(1)
def _get_ipython_height(self):
return "600px"
def _build_component(self, df: "DataFrame") -> "Component":
from manifest import Manifest
import meerkat as mk
def complete_prompt(row: Dict[str, any], example_template: mk.Store[str]):
assert isinstance(row, dict)
output = example_template.format(**row)
return output
@mk.reactive
def format_output_col(output_col):
if output_col is None:
return {
"text": "Template doesn't end with column.",
"classes": "text-red-600 px-2 text-sm",
}
else:
return {
"text": output_col,
"classes": "font-mono font-bold bg-slate-200 rounded-md px-2 text-violet-600 w-fit", # noqa: E501
}
@mk.endpoint
def on_edit(
df: mk.DataFrame, column: str, keyidx: any, posidx: int, value: any
):
df.loc[keyidx, column] = value
@mk.reactive(nested_return=True)
def update_prompt(
df: mk.DataFrame, template: mk.Store[str], instruction: mk.Store[str]
):
"""Update the df with the new prompt template.
This is as simple as returning a view.
"""
df = df.view()
# Extract out the example template from the prompt template.
df["example"] = mk.defer(
df,
function=partial(complete_prompt, example_template=template),
inputs="row",
)
train_df = df[df["is_train"]]
in_context_examples = "\n".join(train_df["example"]())
prompt = f"{instruction} {in_context_examples} {template}"
return df, prompt
@mk.reactive()
def check_example_template(example_template: str, df: mk.DataFrame):
example_template = example_template.strip()
# check if example_template ends with {.*} using a
# regex and extract the content between the brackets.
# Define the regular expression pattern
pattern = r"\{([^}]+)\}$"
# Use re.search to find the match in the example_template string
match = re.search(pattern, example_template)
if match:
# Extract the content between the curly braces using the group() method
content = match.group(1)
if content not in df.columns:
raise ValueError(
f"The column '{content}' does not exist in the dataframe."
)
else:
return None
# raise ValueError("The example template must end with '{column_name}'")
return content
@mk.endpoint()
def run_manifest(
instruct_cmd: str,
df: mk.DataFrame,
output_col: str,
selected: list,
api: str,
):
client_name, engine = api.split("/")
manifest = Manifest(
client_name=client_name,
client_connection=os.getenv("OPENAI_API_KEY"),
engine=engine,
temperature=0,
max_tokens=self.max_tokens,
cache_name="sqlite",
cache_connection=os.path.join(self.manifest_cache_dir, "cache.sqlite"),
)
def _run_manifest(example: mk.Column):
# Format instruct-example-instruct prompt.
out = manifest.run(
[f"{instruct_cmd} {in_context_examples} {x}" for x in example]
)
return out
selected_idxs = df.primary_key.isin(selected).to_pandas()
# Concat all of the in-context examples.
train_df = df[(~selected_idxs) & (df["is_train"])]
in_context_examples = "\n".join(train_df["example"]())
fill_df = df[selected_idxs]
# Filter based on train/abstain/fill
# Only fill in the blanks.
col = output_col
flash_fill = mk.map(
fill_df, function=_run_manifest, is_batched_fn=True, batch_size=4
)
# If the dataframe does not have the column, add it.
if col not in df.columns:
df[col] = ""
df[col][selected_idxs] = flash_fill
df.set(df)
df = df.mark()
instruction_editor = mk.gui.Editor(
code="",
title="Instruction Editor", # Is this paper theoretical or empirical?",
)
example_template_editor = mk.gui.Editor(
code="", # "Abstract: {abstract}, Title: {title}; Answer: {answer}",
title="Training Template Editor",
)
output_col = check_example_template(
example_template=example_template_editor.code, df=df
)
df_view, prompt = update_prompt(
df=df,
template=example_template_editor.code,
instruction=instruction_editor.code,
)
table = mk.gui.Table(
df_view, on_edit=on_edit.partial(df=df), classes="h-[400px]"
)
api_select = mk.gui.core.Select(
values=[
"together/gpt-j-6b",
"together/gpt-2",
"openai/text-davinci-003",
"openai/code-davinci-002",
],
value="together/gpt-j-6b",
)
run_manifest_button = mk.gui.Button(
title="Flash Fill",
icon="Magic",
on_click=run_manifest.partial(
instruct_cmd=instruction_editor.code,
df=df_view,
output_col=output_col,
selected=table.selected,
api=api_select.value,
),
)
run_fn = run_manifest.partial( # noqa: F841
instruct_cmd=instruction_editor.code,
output_col=output_col,
selected=table.selected,
api=api_select.value,
)
formatted_output_col = format_output_col(output_col)
overview_panel = mk.gui.html.flexcol(
[
mk.gui.Text(
"Infer selected rows using in-context learning.",
classes="font-bold text-slate-600 text-sm",
),
mk.gui.Text(
"Specify the instruction and a template for "
"in-context train examples.",
classes="text-slate-600 text-sm",
),
mk.gui.html.div(
[
mk.gui.Text(
"Target column: ", classes="text-slate-600 text-sm"
),
mk.gui.Text(
formatted_output_col["text"],
classes=formatted_output_col["classes"], # noqa: E501
),
],
classes="gap-3 align-middle grid grid-cols-[auto_1fr]",
),
mk.gui.html.grid(
[
run_manifest_button,
api_select,
],
classes="grid grid-cols-[auto_1fr] gap-2",
),
],
classes="items-left mx-4 gap-1",
)
prompt_editor = mk.gui.html.flexcol(
[
instruction_editor,
example_template_editor,
],
classes="flex-1 gap-1",
)
return (
mk.gui.html.div(
[
mk.gui.html.grid(
[overview_panel, prompt_editor],
classes="grid grid-cols-[1fr_3fr] space-x-5",
),
mk.gui.html.div([table], classes="h-full w-screen"),
],
classes="gap-4 h-screen grid grid-rows-[auto_1fr]",
),
prompt,
)
| meerkat-main | meerkat/interactive/app/src/lib/component/contrib/flash_fill/__init__.py |
from typing import Any, Dict, List, Optional
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import EndpointProperty
from ...abstract import Component
class Row(Component):
df: "DataFrame"
columns: List[str]
rename: Dict[str, str] = {}
# The selected key. This should be an element in primary_key_col.
selected_key: Optional[str] = None
title: str = ""
stats: Dict[str, Any] = {"Change": 0.2, "Count": 1000}
# On change should take in 3 arguments:
# - key: the primary key (key)
# - column: the column name (column)
# - value: the new value (value)
on_change: EndpointProperty = None
on_slice_creation: EndpointProperty = None
| meerkat-main | meerkat/interactive/app/src/lib/component/contrib/row/__init__.py |
from ...abstract import BaseComponent
class ChangeList(BaseComponent):
gallery: BaseComponent
gallery_match: BaseComponent
gallery_filter: BaseComponent
gallery_sort: BaseComponent
discover: BaseComponent
plot: BaseComponent
active_slice: BaseComponent
slice_sort: BaseComponent
slice_match: BaseComponent
global_stats: BaseComponent
| meerkat-main | meerkat/interactive/app/src/lib/component/contrib/change_list/__init__.py |
import hashlib
from typing import Sequence
from meerkat.dataframe import DataFrame
from meerkat.interactive.app.src.lib.component.abstract import Component
from meerkat.interactive.endpoint import Endpoint, EndpointProperty, endpoint
from meerkat.interactive.graph import Store, reactive, unmarked
@endpoint
def base_on_run(
new_query: str,
query: str,
df: DataFrame,
criteria_df: DataFrame,
manifest_session,
):
print(new_query)
if new_query == "" or new_query == "__default__":
query.set("__default__")
return
variables = {}
exec(new_query, None, variables)
prompt, answers = variables["prompt"], variables["answers"]
df = df.view()
def _run_inference(question: Sequence[str]):
return manifest_session.run(
[prompt.format(question=question) for question in question]
)
# df = df.sample(100) # TODO: remove this
# create a column name out of a hash of the query
print("endpoint", new_query)
column_name = _hash_query(new_query)
if column_name not in criteria_df:
out = df.map(_run_inference, is_batched_fn=True, batch_size=200, pbar=True)
criteria_df[column_name] = criteria_df.primary_key.isin(
df[out.isin(answers)].primary_key
)
query.set(new_query)
@reactive
def filter_df(df: DataFrame, criteria_df: DataFrame, query: str):
df = df[
df.primary_key.isin(criteria_df.primary_key[criteria_df[_hash_query(query)]])
]
return df
class FMFilter(Component):
query: str
criteria_df: DataFrame
on_run: EndpointProperty = None
def __init__(self, df=DataFrame, on_run: Endpoint = None, manifest_session=None):
query = Store("__default__")
with unmarked():
criteria_df = df[[df.primary_key_name]]
criteria_df[_hash_query("__default__")] = True
manifest_session = manifest_session
partial_on_run = base_on_run.partial(
df=df,
query=query,
criteria_df=criteria_df,
manifest_session=manifest_session,
)
if on_run is not None:
on_run = partial_on_run.compose(on_run)
else:
on_run = partial_on_run
super().__init__(query=query, criteria_df=criteria_df, on_run=on_run)
def __call__(self, df: DataFrame):
out = filter_df(df, criteria_df=self.criteria_df, query=self.query)
return out
def _hash_query(query: str):
return "fm_" + hashlib.sha256(query.encode()).hexdigest()[:8]
| meerkat-main | meerkat/interactive/app/src/lib/component/contrib/fm_filter/__init__.py |
from ...abstract import Component
class GlobalStats(Component):
v1_name: str
v2_name: str
v1_mean: float
v2_mean: float
shift: float
inconsistency: float
metric: str = "Accuracy"
| meerkat-main | meerkat/interactive/app/src/lib/component/contrib/global_stats/__init__.py |
import datetime
from typing import Any, Dict, List, Optional, Union
from meerkat.interactive.app.src.lib.component.abstract import Component, Slottable
from meerkat.interactive.endpoint import Endpoint
from meerkat.tools.utils import classproperty
from .types import (
ActivityType,
Buttonshadows,
ButtonType,
DrawerTransitionTypes,
FormColorType,
GroupTimelineType,
LinkType,
Placement,
ReviewType,
SiteType,
SizeType,
TransitionTypes,
number,
)
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
class FlowbiteSvelteMixin:
@classproperty
def library(cls):
return "flowbite-svelte"
@classproperty
def namespace(cls):
return "flowbite"
class Accordion(Slottable, FlowbiteSvelteMixin, Component):
multiple: bool = False
flush: bool = False
activeClasses: str = "bg-gray-100 dark:bg-gray-800 text-gray-900 "
"dark:text-white focus:ring-4 focus:ring-gray-200 dark:focus:ring-gray-800"
inactiveClasses: str = (
"text-gray-500 dark:text-gray-400 hover:bg-gray-100 hover:dark:bg-gray-800"
)
defaultClass: str = "text-gray-500 dark:text-gray-400"
class AccordionItem(Slottable, FlowbiteSvelteMixin, Component):
open: bool = False
activeClasses: str = None
inactiveClasses: str = None
defaultClass: str = "flex items-center justify-between w-full font-medium "
"text-left group-first:rounded-t-xl"
transitionType: Literal["slide", "fade"] = "slide"
transitionParams: dict = {}
class Alert(Slottable, FlowbiteSvelteMixin, Component):
dismissable: bool = False
accent: bool = False
color: Literal[
"blue", "dark", "red", "green", "yellow", "indigo", "purple", "pink"
] = "blue"
class Avatar(Slottable, FlowbiteSvelteMixin, Component):
src: str = ""
href: str = None
rounded: bool = False
border: bool = False
stacked: bool = False
dot: dict = None
alt: str = ""
size: SizeType = "md"
classes: str = None
class Badge(Slottable, FlowbiteSvelteMixin, Component):
color: Literal[
"blue", "dark", "red", "green", "yellow", "indigo", "purple", "pink"
] = "blue"
large: bool = False
border: bool = False
href: str = None
rounded: bool = False
index: bool = False
dismissable: bool = False
class Breadcrumb(Slottable, FlowbiteSvelteMixin, Component):
solid: bool = False
navClass: str = "flex"
solidClass: str = "flex px-5 py-3 text-gray-700 border border-gray-200 "
"rounded-lg bg-gray-50 dark:bg-gray-800 dark:border-gray-700"
olClass: str = "inline-flex items-center space-x-1 md:space-x-3"
class BreadcrumbItem(Slottable, FlowbiteSvelteMixin, Component):
home: bool = False
href: str = None
linkClass: str = "ml-1 text-sm font-medium text-gray-700 hover:text-gray-900 "
"md:ml-2 dark:text-gray-400 dark:hover:text-white"
spanClass: str = "ml-1 text-sm font-medium text-gray-500 md:ml-2 "
"dark:text-gray-400"
homeClass: str = "inline-flex items-center text-sm font-medium "
"text-gray-700 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white"
class Button(Slottable, FlowbiteSvelteMixin, Component):
classes: str = None
pill: bool = False
outline: bool = False
gradient: bool = False
size: SizeType = "md"
href: str = None
btnClass: str = None
type: ButtonType = "button"
color: Literal[
"alternative",
"blue",
"cyan",
"dark",
"light",
"lime",
"green",
"pink",
"primary",
"red",
"teal",
"yellow",
"purple",
"purpleToBlue",
"cyanToBlue",
"greenToBlue",
"purpleToPink",
"pinkToOrange",
"tealToLime",
"redToYellow",
] = "blue"
shadow: Optional[Buttonshadows] = None
on_change: Endpoint = None
on_click: Endpoint = None
on_keydown: Endpoint = None
on_keyup: Endpoint = None
on_mouseenter: Endpoint = None
on_mouseleave: Endpoint = None
class ButtonGroup(Slottable, FlowbiteSvelteMixin, Component):
size: SizeType = "md"
divClass: str = "inline-flex rounded-lg shadow-sm"
on_blur: Endpoint = None
on_change: Endpoint = None
on_click: Endpoint = None
on_focus: Endpoint = None
on_keydown: Endpoint = None
on_keyup: Endpoint = None
on_mouseenter: Endpoint = None
on_mouseleave: Endpoint = None
class Card(Slottable, FlowbiteSvelteMixin, Component):
href: str = None
horizontal: bool = False
reverse: bool = False
img: str = None
padding: Literal["none", "sm", "md", "lg", "xl"] = "lg"
size: SizeType = "sm"
# Frame options, passed as $$restProps
tag: Literal["div", "a"] = "div"
color: Literal[
"gray",
"red",
"yellow",
"green",
"indigo",
"default",
"purple",
"pink",
"blue",
"light",
"dark",
"dropdown",
"navbar",
"navbarUl",
"form",
"none",
] = "default"
rounded: bool = False
border: bool = False
shadow: bool = False
class Carousel(Slottable, FlowbiteSvelteMixin, Component):
showIndicators: bool = True
showCaptions: bool = True
showThumbs: bool = True
images: List[Dict[str, Any]] = []
slideControls: bool = True
loop: bool = False
duration: int = 2000
divClass: str = "overflow-hidden relative h-56 rounded-lg sm:h-64 xl:h-80 2xl:h-96"
indicatorDivClass: str = (
"flex absolute bottom-5 left-1/2 z-30 space-x-3 -translate-x-1/2"
)
captionClass: str = (
"h-10 bg-gray-300 dark:bg-gray-700 dark:text-white p-2 my-2 text-center"
)
indicatorClass: str = (
"w-3 h-3 rounded-full bg-gray-100 hover:bg-gray-300 opacity-60"
)
slideClass: str = ""
class CarouselTransition(Slottable, FlowbiteSvelteMixin, Component):
showIndicators: bool = True
showCaptions: bool = True
showThumbs: bool = True
images: List[Dict[str, Any]] = []
slideControls: bool = True
transitionType: TransitionTypes = "fade"
transitionParams: dict = {} # TransitionParamTypes
loop: bool = False
duration: int = 2000
divClass: str = "overflow-hidden relative h-56 rounded-lg sm:h-64 xl:h-80 2xl:h-96"
indicatorDivClass: str = (
"flex absolute bottom-5 left-1/2 z-30 space-x-3 -translate-x-1/2"
)
captionClass: str = (
"h-10 bg-gray-300 dark:bg-gray-700 dark:text-white p-2 my-2 text-center"
)
indicatorClass: str = (
"w-3 h-3 rounded-full bg-gray-100 hover:bg-gray-300 opacity-60"
)
class DarkMode(Slottable, FlowbiteSvelteMixin, Component):
btnClass: str = (
"text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 "
"focus:outline-none focus:ring-4 focus:ring-gray-200 dark:focus:ring-gray-700 "
"rounded-lg text-sm p-2.5"
)
class Drawer(Slottable, FlowbiteSvelteMixin, Component):
activateClickOutside: bool = True
hidden: bool = True
position: Literal["fixed", "absolute"] = "fixed"
leftOffset: str = "inset-y-0 left-0"
rightOffset: str = "inset-y-0 right-0"
topOffset: str = "inset-x-0 top-0"
bottomOffset: str = "inset-x-0 bottom-0"
width: str = "w-80"
backdrop: bool = True
bgColor: str = "bg-gray-900"
bgOpacity: str = "bg-opacity-75"
placement: Literal["left", "right", "top", "bottom"] = "left"
# id: str = "drawer-example"
divClass: str = "overflow-y-auto z-50 p-4 bg-white dark:bg-gray-800"
transitionParams: dict = {} # DrawerTransitionParamTypes
transitionType: DrawerTransitionTypes = "fly"
class Dropdown(Slottable, FlowbiteSvelteMixin, Component):
open: bool = False
frameClass: str = ""
# Configure slots for header and footer
class DropdownItem(Slottable, FlowbiteSvelteMixin, Component):
defaultClass: str = (
"font-medium py-2 px-4 text-sm hover:bg-gray-100 dark:hover:bg-gray-600"
)
href: str = None
# Events
on_blur: Endpoint = None
on_change: Endpoint = None
on_click: Endpoint = None
on_focus: Endpoint = None
on_keydown: Endpoint = None
on_keyup: Endpoint = None
on_mouseenter: Endpoint = None
on_mouseleave: Endpoint = None
class DropdownDivider(Slottable, FlowbiteSvelteMixin, Component):
divClass: str = "my-1 h-px bg-gray-100 dark:bg-gray-600"
class DropdownHeader(Slottable, FlowbiteSvelteMixin, Component):
divClass: str = "py-2 px-4 text-gray-700 dark:text-white"
divider: bool = True
class Footer(Slottable, FlowbiteSvelteMixin, Component):
customClass: str = ""
footerType: Literal[
"custom", "sitemap", "default", "logo", "socialmedia"
] = "default"
class FooterBrand(Slottable, FlowbiteSvelteMixin, Component):
aClass: str = "flex items-center"
spanClass: str = (
"self-center text-2xl font-semibold whitespace-nowrap dark:text-white"
)
imgClass: str = "mr-3 h-8"
href: str = ""
src: str = ""
alt: str = ""
name: str = ""
target: str = None
class FooterCopyright(Slottable, FlowbiteSvelteMixin, Component):
spanClass: str = "block text-sm text-gray-500 sm:text-center dark:text-gray-400"
aClass: str = "hover:underline"
year: number = int(datetime.date.today().strftime("%Y")) # current year
href: str = ""
by: str = ""
target: str = None
class FooterIcon(Slottable, FlowbiteSvelteMixin, Component):
href: str = ""
ariaLabel: str = ""
aClass: str = "text-gray-500 hover:text-gray-900 dark:hover:text-white"
target: str = None
class FooterLink(Slottable, FlowbiteSvelteMixin, Component):
liClass: str = "mr-4 last:mr-0 md:mr-6"
aClass: str = "hover:underline"
href: str = ""
target: str = None
class FooterLinkGroup(Slottable, FlowbiteSvelteMixin, Component):
ulClass: str = "text-gray-600 dark:text-gray-400"
class Indicator(Slottable, FlowbiteSvelteMixin, Component):
color: Literal[
"gray",
"dark",
"blue",
"green",
"red",
"purple",
"indigo",
"yellow",
"teal",
"none",
] = "gray"
rounded: bool = False
size: SizeType = "md"
border: bool = False
placement: Literal[
"top-left",
"top-center",
"top-right",
"center-left",
"center",
"center-right",
"bottom-left",
"bottom-center",
"bottom-right",
] = None
offset: bool = True
class Kbd(Slottable, FlowbiteSvelteMixin, Component):
kbdClass: str = "text-xs font-semibold text-gray-800 bg-gray-100 "
"border border-gray-200 rounded-lg dark:bg-gray-600 "
"dark:text-gray-100 dark:border-gray-500"
class ArrowKeyDown(Slottable, FlowbiteSvelteMixin, Component):
svgClass: str = "w-4 h-4"
class ArrowKeyLeft(Slottable, FlowbiteSvelteMixin, Component):
svgClass: str = "w-4 h-4"
class ArrowKeyRight(Slottable, FlowbiteSvelteMixin, Component):
svgClass: str = "w-4 h-4"
class ArrowKeyUp(Slottable, FlowbiteSvelteMixin, Component):
svgClass: str = "w-4 h-4"
# class ListGroup(Slottable, FlowbiteSvelteMixin, Component):
# items: List[ListGroupItemType] = []
# active: bool = False
# classes: str = ""
# class ListGroupItem(Slottable, FlowbiteSvelteMixin, Component):
# classes: str = ""
# # Events
# on_blur: Endpoint = None
# on_change: Endpoint = None
# on_click: Endpoint = None
# on_focus: Endpoint = None
# on_keydown: Endpoint = None
# on_keypress: Endpoint = None
# on_keyup: Endpoint = None
# on_mouseenter: Endpoint = None
# on_mouseleave: Endpoint = None
# on_mouseover: Endpoint = None
class MegaMenu(Slottable, FlowbiteSvelteMixin, Component):
classes: str = None
items: List[LinkType] = []
open: bool = False
full: bool = False
class Modal(Slottable, FlowbiteSvelteMixin, Component):
open: bool = False
title: str = ""
size: SizeType = "md"
placement: Literal[
"top-left",
"top-center",
"top-right",
"center-left",
"center",
"center-right",
"bottom-left",
"bottom-center",
"bottom-right",
] = "center"
autoclose: bool = False
permanent: bool = False
backdropClasses: str = "bg-gray-900 bg-opacity-50 dark:bg-opacity-80"
on_hide: Endpoint = None
on_open: Endpoint = None
class Navbar(Slottable, FlowbiteSvelteMixin, Component):
navClass: str = "px-2 sm:px-4 py-2.5 w-full"
navDivClass: str = "mx-auto flex flex-wrap justify-between items-center "
fluid: bool = True
color: Literal[
"gray",
"red",
"yellow",
"green",
"indigo",
"default",
"purple",
"pink",
"blue",
"light",
"dark",
"dropdown",
"navbar",
"navbarUl",
"form",
"none",
] = "navbar"
class NavBrand(Slottable, FlowbiteSvelteMixin, Component):
href: str = ""
class NavLi(Slottable, FlowbiteSvelteMixin, Component):
href: str = ""
active: bool = False
activeClass: str = "text-white bg-blue-700 md:bg-transparent "
"md:text-blue-700 md:dark:text-white dark:bg-blue-600 md:dark:bg-transparent"
nonActiveClass: str = "text-gray-700 hover:bg-gray-100 md:hover:bg-transparent "
"md:border-0 md:hover:text-blue-700 dark:text-gray-400 md:dark:hover:text-white "
"dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent"
class NavUl(Slottable, FlowbiteSvelteMixin, Component):
divClass: str = "w-full md:block md:w-auto"
ulClass: str = "flex flex-col p-4 mt-4 md:flex-row md:space-x-8 md:mt-0 "
"md:text-sm md:font-medium"
hidden: bool = True
# slideParams: SlideParams = {delay: 250, duration: 500, easing: quintOut}
class Pagination(Slottable, FlowbiteSvelteMixin, Component):
pages: List[LinkType] = []
activeClass: str = "text-blue-600 border border-gray-300 bg-blue-50 "
"hover:bg-blue-100 hover:text-blue-700 dark:border-gray-700 "
"dark:bg-gray-700 dark:text-white"
normalClass: str = "text-gray-500 bg-white hover:bg-gray-100 "
"hover:text-gray-700 dark:bg-gray-800 dark:border-gray-700 "
"dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white"
ulClass: str = "inline-flex -space-x-px items-center"
table: bool = False
class PaginationItem(Slottable, FlowbiteSvelteMixin, Component):
href: str = None
active: bool = False
activeClass: str = ""
normalClass: str = "text-gray-500 bg-white hover:bg-gray-100 "
"hover:text-gray-700 dark:bg-gray-800 dark:border-gray-700 "
"dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white"
class Popover(Slottable, FlowbiteSvelteMixin, Component):
title: str = ""
defaultClass: str = "py-2 px-3"
# class Popper(Slottable, FlowbiteSvelteMixin, Component):
# activeContent: bool = False
# arrow: bool = True
# offset: number = 8
# placement: Placement = "top"
# trigger: Literal["hover", "click"] = "hover"
# triggeredBy: str = None
# strategy: Literal["absolute", "fixed"] = "absolute"
# open: bool = False
# yOnly: bool = False
# class Frame(Slottable, FlowbiteSvelteMixin, Component):
# tag: str = "div"
# color: Literal[
# "gray",
# "red",
# "yellow",
# "green",
# "indigo",
# "default",
# "purple",
# "pink",
# "blue",
# "light",
# "dark",
# "dropdown",
# "navbar",
# "navbarUl",
# "form",
# "none",
# ] = "default"
# rounded: bool = False
# border: bool = False
# shadow: bool = False
# # transition: TransitionFunc = None
# params: object = {}
# # node: HTMLElement = None
# # use: Action = noop
# options: object = {}
class Progressbar(Slottable, FlowbiteSvelteMixin, Component):
progress: number = 45
size: Literal["h-2.5", "h-3", "h-4", "h-5"] = "h-2.5"
labelInside: bool = False
labelOutside: str = ""
color: Literal[
"blue", "gray", "red", "green", "yellow", "purple", "indigo"
] = "blue"
labelInsideClass: str = (
"text-blue-100 text-xs font-medium text-center p-0.5 leading-none "
"rounded-full"
)
class Rating(Slottable, FlowbiteSvelteMixin, Component):
divClass: str = "flex items-center"
size: str = "24"
total: number = 5
rating: number = 4
ceil: bool = False
count: bool = False
class AdvancedRating(Slottable, FlowbiteSvelteMixin, Component):
divClass: str = "flex items-center mt-4"
labelClass: str = "text-sm font-medium text-blue-600 dark:text-blue-500"
ratingDivClass: str = "mx-4 w-2/4 h-5 bg-gray-200 rounded dark:bg-gray-700"
ratingClass: str = "h-5 bg-yellow-400 rounded"
rightLabelClass: str = "text-sm font-medium text-blue-600 dark:text-blue-500"
unit: str = "%"
class ScoreRating(Slottable, FlowbiteSvelteMixin, Component):
desc1Class: str = "bg-blue-100 w-8 text-blue-800 text-sm font-semibold "
"inline-flex items-center p-1.5 rounded dark:bg-blue-200 dark:text-blue-800"
desc2Class: str = "ml-2 w-24 font-medium text-gray-900 dark:text-white"
desc3spanClass: str = "mx-2 w-1 h-1 bg-gray-900 rounded-full dark:bg-gray-500"
desc3pClass: str = "text-sm w-24 font-medium text-gray-500 dark:text-gray-400"
class RatingComment(Slottable, FlowbiteSvelteMixin, Component):
ceil: bool = False
helpfullink: str = ""
abuselink: str = ""
class Review(Slottable, FlowbiteSvelteMixin, Component):
review: ReviewType = None
articleClass: str = "md:gap-8 md:grid md:grid-cols-3"
divClass: str = "flex items-center mb-6 space-x-4"
imgClass: str = "w-10 h-10 rounded-full"
ulClass: str = "space-y-4 text-sm text-gray-500 dark:text-gray-400"
liClass: str = "flex items-center"
class Sidebar(Slottable, FlowbiteSvelteMixin, Component):
asideClass: str = "w-64"
class SidebarBrand(Slottable, FlowbiteSvelteMixin, Component):
site: SiteType = None
class SidebarCta(Slottable, FlowbiteSvelteMixin, Component):
divWrapperClass: str = "p-4 mt-6 bg-blue-50 rounded-lg dark:bg-blue-900"
divClass: str = "flex items-center mb-3"
spanClass: str = "bg-orange-100 text-orange-800 text-sm font-semibold "
"mr-2 px-2.5 py-0.5 rounded dark:bg-orange-200 dark:text-orange-900"
label: str = ""
class SidebarDropdownItem(Slottable, FlowbiteSvelteMixin, Component):
aClass: str = "flex items-center p-2 pl-11 w-full text-base font-normal "
"text-gray-900 rounded-lg transition duration-75 group hover:bg-gray-100 "
"dark:text-white dark:hover:bg-gray-700"
href: str = ""
label: str = ""
activeClass: str = "flex items-center p-2 pl-11 text-base font-normal "
"text-gray-900 bg-gray-200 dark:bg-gray-700 rounded-lg dark:text-white "
"hover:bg-gray-100 dark:hover:bg-gray-700"
active: bool = False
# Events
on_blur: Endpoint = None
on_click: Endpoint = None
on_focus: Endpoint = None
on_keydown: Endpoint = None
on_keypress: Endpoint = None
on_keyup: Endpoint = None
on_mouseenter: Endpoint = None
on_mouseleave: Endpoint = None
on_mouseover: Endpoint = None
class SidebarDropdownWrapper(Slottable, FlowbiteSvelteMixin, Component):
btnClass: str = "flex items-center p-2 w-full text-base font-normal "
"text-gray-900 rounded-lg transition duration-75 group hover:bg-gray-100 "
"dark:text-white dark:hover:bg-gray-700"
label: str = ""
spanClass: str = "flex-1 ml-3 text-left whitespace-nowrap"
ulClass: str = "py-2 space-y-2"
isOpen: bool = False
class SidebarGroup(Slottable, FlowbiteSvelteMixin, Component):
ulClass: str = "space-y-2"
borderClass: str = "pt-4 mt-4 border-t border-gray-200 dark:border-gray-700"
border: bool = False
class SidebarItem(Slottable, FlowbiteSvelteMixin, Component):
aClass: str = "flex items-center p-2 text-base font-normal text-gray-900 "
"rounded-lg dark:text-white hover:bg-gray-100 dark:hover:bg-gray-700"
href: str = ""
label: str = ""
spanClass: str = "ml-3"
activeClass: str = "flex items-center p-2 text-base font-normal text-gray-900 "
"bg-gray-200 dark:bg-gray-700 rounded-lg dark:text-white hover:bg-gray-100 "
"dark:hover:bg-gray-700"
active: bool = False
# Events
on_blur: Endpoint = None
on_click: Endpoint = None
on_focus: Endpoint = None
on_keydown: Endpoint = None
on_keypress: Endpoint = None
on_keyup: Endpoint = None
on_mouseenter: Endpoint = None
on_mouseleave: Endpoint = None
on_mouseover: Endpoint = None
class SidebarWrapper(Slottable, FlowbiteSvelteMixin, Component):
divClass: str = "overflow-y-auto py-4 px-3 bg-gray-50 rounded dark:bg-gray-800"
asideClass: str = "w-64"
class SpeedDial(Slottable, FlowbiteSvelteMixin, Component):
defaultClass: str = "fixed right-6 bottom-6"
placement: Placement = "top"
pill: bool = True
tooltip: Union[Placement, Literal["none"]] = "left"
trigger: Literal["hover", "click"] = "hover"
textOutside: bool = False
# id: str = str(uuid.uuid4())
# Events
on_click: Endpoint = None
class SpeedDialButton(Slottable, FlowbiteSvelteMixin, Component):
pass
class Spinner(Slottable, FlowbiteSvelteMixin, Component):
color: Literal[
"blue", "gray", "green", "red", "yellow", "pink", "purple", "white"
] = "blue"
bg: str = "text-gray-300"
size: str = "8"
currentFill: str = "currentFill"
currentColor: str = "currentColor"
class Tabs(Slottable, FlowbiteSvelteMixin, Component):
style: Literal["full", "pill", "underline", "none"] = "none"
defaultClass: str = "flex flex-wrap space-x-2"
contentClass: str = "p-4 bg-gray-50 rounded-lg dark:bg-gray-800 mt-4"
divider: bool = True
activeClasses: str = (
"p-4 text-blue-600 bg-gray-100 rounded-t-lg dark:bg-gray-800 "
"dark:text-blue-500"
)
inactiveClasses: str = "p-4 text-gray-500 rounded-t-lg hover:text-gray-600 "
"hover:bg-gray-50 dark:text-gray-400 dark:hover:bg-gray-800 "
"dark:hover:text-gray-300"
class TabItem(Slottable, FlowbiteSvelteMixin, Component):
open: bool = False
title: str = "Tab title"
activeClasses: str = ""
inactiveClasses: str = ""
defaultClass: str = (
"inline-block text-sm font-medium text-center disabled:cursor-not-allowed"
)
class Table(Slottable, FlowbiteSvelteMixin, Component):
divClass: str = "relative overflow-x-auto"
striped: bool = False
hoverable: bool = False
noborder: bool = False
shadow: bool = False
color: Literal[
"blue",
"green",
"red",
"yellow",
"purple",
"indigo",
"pink",
"default",
"custom",
] = "default"
class TableBodyCell(Slottable, FlowbiteSvelteMixin, Component):
tdClass: str = "px-6 py-4 whitespace-nowrap font-medium "
class TableBodyRow(Slottable, FlowbiteSvelteMixin, Component):
# TODO: figure out how to get context
color: Literal[
"blue", "green", "red", "yellow", "purple", "default", "custom"
] = "purple" # getContext("color")
class TableSearch(Slottable, FlowbiteSvelteMixin, Component):
divClass: str = "relative overflow-x-auto shadow-md sm:rounded-lg"
inputValue: str = ""
striped: bool = False
hoverable: bool = False
placeholder: str = "Search"
color: Literal[
"blue", "green", "red", "yellow", "purple", "default", "custom"
] = "default"
class TableHead(Slottable, FlowbiteSvelteMixin, Component):
theadClass: str = "text-xs uppercase"
defaultRow: bool = True
class Timeline(Slottable, FlowbiteSvelteMixin, Component):
customClass: str = ""
order: Literal[
"default", "vertical", "horizontal", "activity", "group", "custom"
] = "default"
class TimelineItem(Slottable, FlowbiteSvelteMixin, Component):
title: str = ""
date: str = ""
customDiv: str = ""
customTimeClass: str = ""
class Checkbox(Slottable, FlowbiteSvelteMixin, Component):
color: FormColorType = "blue"
title: str = ""
date: str = ""
class TimelineHorizontal(Slottable, FlowbiteSvelteMixin, Component):
olClass: str = "items-center sm:flex"
class TimelineItemHorizontal(Slottable, FlowbiteSvelteMixin, Component):
title: str = ""
date: str = ""
class Toast(Slottable, FlowbiteSvelteMixin, Component):
color: Literal[
"gray",
"red",
"yellow",
"green",
"indigo",
"default",
"purple",
"pink",
"blue",
"light",
"dark",
"dropdown",
"navbar",
"navbarUl",
"form",
"none",
] = "blue"
simple: bool = False
position: Literal[
"top-left", "top-right", "bottom-left", "bottom-right", "none"
] = "none"
open: bool = True
divClass: str = "w-full max-w-xs p-4"
classes: str = None
class Tooltip(Slottable, FlowbiteSvelteMixin, Component):
style: Literal["dark", "light", "auto", "custom"] = "dark"
defaultClass: str = "py-2 px-3 text-sm font-medium"
class Activity(Slottable, FlowbiteSvelteMixin, Component):
olClass: str = "relative border-l border-gray-200 dark:border-gray-700"
class ActivityItem(Slottable, FlowbiteSvelteMixin, Component):
activities: List[ActivityType] = []
class Group(Slottable, FlowbiteSvelteMixin, Component):
divClass: str = "p-5 mb-4 bg-gray-50 rounded-lg border border-gray-100 "
"dark:bg-gray-800 dark:border-gray-700"
timeClass: str = "text-lg font-semibold text-gray-900 dark:text-white"
date: str = "" # date: Union[Date, str] = ""
class GroupItem(Slottable, FlowbiteSvelteMixin, Component):
timelines: List[GroupTimelineType] = []
# "blue", "red", "green", "yellow", "indigo", "purple", "pink"
# ] = "blue" # TODO: check that these are the right colors
custom: bool = False
inline: bool = False
group: Union[number, str] = ""
value: Union[number, str] = ""
on_change: Endpoint = None
on_click: Endpoint = None
on_keydown: Endpoint = None
on_keyup: Endpoint = None
on_mouseenter: Endpoint = None
on_mouseleave: Endpoint = None
on_paste: Endpoint = None
class FloatingLabelInput(FlowbiteSvelteMixin, Component):
# id: str = "" # determine if this should be uuid
style: Literal["filled", "outlined", "standard"] = "standard"
type: Literal["text"] = "text" # TODO: add more input types
size: Literal["small", "default"] = "default"
color: Literal["base", "green", "red"] = "base"
value: str = ""
label: str = ""
on_blur: Endpoint = None
on_change: Endpoint = None
on_click: Endpoint = None
on_focus: Endpoint = None
on_keydown: Endpoint = None
on_keypress: Endpoint = None
on_keyup: Endpoint = None
on_mouseenter: Endpoint = None
on_mouseleave: Endpoint = None
on_mouseover: Endpoint = None
on_paste: Endpoint = None
class Radio(Slottable, FlowbiteSvelteMixin, Component):
color: Literal[
"blue", "red", "green", "yellow", "indigo", "purple", "pink"
] = "blue"
custom: bool = False
inline: bool = False
group: Union[number, str] = ""
value: Union[number, str] = ""
on_blur: Endpoint = None
on_change: Endpoint = None
on_click: Endpoint = None
on_focus: Endpoint = None
on_keydown: Endpoint = None
on_keypress: Endpoint = None
on_keyup: Endpoint = None
on_mouseenter: Endpoint = None
on_mouseleave: Endpoint = None
on_mouseover: Endpoint = None
on_paste: Endpoint = None
class Range(FlowbiteSvelteMixin, Component):
value: number
size: Literal["sm", "md", "lg"] = "md"
min: number = None
max: number = None
step: number = None
on_change: Endpoint = None
on_click: Endpoint = None
on_keydown: Endpoint = None
on_keypress: Endpoint = None
on_keyup: Endpoint = None
class Search(FlowbiteSvelteMixin, Component):
size: Literal["sm", "md", "lg"] = "lg"
placeholder: str = "Search"
value: Union[str, number] = ""
on_blur: Endpoint = None
on_change: Endpoint = None
on_click: Endpoint = None
on_focus: Endpoint = None
on_keydown: Endpoint = None
on_keypress: Endpoint = None
on_keyup: Endpoint = None
on_mouseenter: Endpoint = None
on_mouseleave: Endpoint = None
on_mouseover: Endpoint = None
on_paste: Endpoint = None
class Select(Slottable, FlowbiteSvelteMixin, Component):
items: list
value: Union[str, number]
placeholder: str = "Choose option ..."
underline: bool = False
size: Literal["sm", "md", "lg"] = "md"
on_change: Endpoint = None
on_input: Endpoint = None
class Textarea(FlowbiteSvelteMixin, Component):
value: str = ""
rows: int = 3
placeholder: str = ""
classes: str = None
on_blur: Endpoint = None
on_change: Endpoint = None
on_click: Endpoint = None
on_focus: Endpoint = None
on_input: Endpoint = None
on_keydown: Endpoint = None
on_keypress: Endpoint = None
on_keyup: Endpoint = None
on_mouseenter: Endpoint = None
on_mouseleave: Endpoint = None
on_mouseover: Endpoint = None
on_paste: Endpoint = None
class Toggle(Slottable, FlowbiteSvelteMixin, Component):
size: Literal["small", "default", "large"] = "default"
group: List[Union[str, number]] = ()
value: Union[str, number] = ""
checked: bool = False
on_change: Endpoint = None
on_click: Endpoint = None
"""Typography."""
class A(Slottable, FlowbiteSvelteMixin, Component):
href: str = "#"
color: str = "text-blue-600 dark:text-blue-500"
aClass: str = "inline-flex items-center hover:underline"
class Blockquote(Slottable, FlowbiteSvelteMixin, Component):
border: bool = False
italic: bool = True
borderClass: str = "border-l-4 border-gray-300 dark:border-gray-500"
bgClass: str = "bg-gray-50 dark:bg-gray-800"
bg: bool = False
baseClass: str = "font-semibold text-gray-900 dark:text-white"
alignment: Literal["left", "center", "right"] = "left"
size: Literal[
"xs",
"sm",
"base",
"lg",
"xl",
"2xl",
"3xl",
"4xl",
"5xl",
"6xl",
"7xl",
"8xl",
"9xl",
] = "lg"
class DescriptionList(Slottable, FlowbiteSvelteMixin, Component):
tag: Literal["dt", "dd"] = ""
dtClass: str = "text-gray-500 md:text-lg dark:text-gray-400"
ddClass: str = "text-lg font-semibold"
class Heading(Slottable, FlowbiteSvelteMixin, Component):
tag: Literal["h1", "h2", "h3", "h4", "h5", "h6"] = "h1"
color: str = "text-gray-900 dark:text-white"
customSize: str = ""
class Hr(Slottable, FlowbiteSvelteMixin, Component):
icon: bool = False
width: str = "w-full"
height: str = "h-px"
divClass: str = "inline-flex justify-center items-center w-full"
hrClass: str = "bg-gray-200 rounded border-0 dark:bg-gray-700"
iconDivClass: str = "absolute left-1/2 px-4 bg-white -translate-x-1/2 "
textSpanClass: str = "absolute left-1/2 px-3 font-medium text-gray-900 "
"bg-white -translate-x-1/2 dark:text-white "
middleBgColor: str = "dark:bg-gray-900"
class Layout(Slottable, FlowbiteSvelteMixin, Component):
divClass: str = "grid"
cols: str = "grid-cols-1 sm:grid-cols-2"
gap: number = 4
class Li(Slottable, FlowbiteSvelteMixin, Component):
icon: bool = False
liClass: str = ""
class List(Slottable, FlowbiteSvelteMixin, Component):
tag: Literal["ul", "ol", "dl"] = "ul"
list: Literal["disc", "none", "decimal"] = "disc"
position: Literal["inside", "outside"] = "inside"
color: str = "text-gray-500 dark:text-gray-400"
olClass: str = "list-decimal list-inside"
ulClass: str = "max-w-md"
dlClass: str = "max-w-md divide-y divide-gray-200 dark:divide-gray-700"
class Mark(Slottable, FlowbiteSvelteMixin, Component):
color: str = "text-white dark:bg-blue-500"
bgColor: str = "bg-blue-600"
markClass: str = "px-2 rounded"
class P(Slottable, FlowbiteSvelteMixin, Component):
color: str = "text-gray-900 dark:text-white"
height: Literal["normal", "relaxed", "loose"] = "normal"
align: Literal["left", "center", "right"] = "left"
justify: bool = False
italic: bool = False
firstupper: bool = False
upperClass: str = "first-line:uppercase first-line:tracking-widest "
"first-letter:text-7xl first-letter:font-bold first-letter:text-gray-900 "
"dark:first-letter:text-gray-100 first-letter:mr-3 first-letter:float-left"
opacity: Union[number, None] = None
whitespace: Literal["normal", "nowrap", "pre", "preline", "prewrap"] = "normal"
size: Literal[
"xs",
"sm",
"base",
"lg",
"xl",
"2xl",
"3xl",
"4xl",
"5xl",
"6xl",
"7xl",
"8xl",
"9xl",
] = "base"
space: Literal[
"tighter",
"tight",
"normal",
"wide",
"wider",
"widest",
None,
] = None
weight: Literal[
"thin",
"extralight",
"light",
"normal",
"medium",
"semibold",
"bold",
"extrabold",
"black",
] = "normal"
class Secondary(Slottable, FlowbiteSvelteMixin, Component):
color: str = "text-gray-500 dark:text-gray-400"
secondaryClass: str = "font-semibold"
class Span(Slottable, FlowbiteSvelteMixin, Component):
italic: bool = False
underline: bool = False
linethrough: bool = False
uppercase: bool = False
gradient: bool = False
highlight: bool = False
highlightClass: str = "text-blue-600 dark:text-blue-500"
decorationClass: str = "decoration-2 decoration-blue-400 "
"dark:decoration-blue-600"
gradientClass: str = (
"text-transparent bg-clip-text bg-gradient-to-r to-emerald-600 "
"from-sky-400"
)
__all__ = [
"Accordion",
"AccordionItem",
"Button",
"Card",
"Dropdown",
"DropdownItem",
"DropdownDivider",
"DropdownHeader",
]
| meerkat-main | meerkat/interactive/app/src/lib/component/flowbite/__init__.py |
from dataclasses import dataclass
from typing import Callable, List, Optional, Union
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
number = Union[int, float]
AlignType = Literal["text-center", "text-left", "text-right"]
ButtonType = Literal["button", "submit", "reset"]
Buttontypes = Literal[
"blue",
"blue-outline",
"dark",
"dark-outline",
"light",
"green",
"green-outline",
"red",
"red-outline",
"yellow",
"yellow-outline",
"purple",
"purple-outline",
]
Buttonshadows = Literal[
"blue", "green", "cyan", "teal", "lime", "red", "pink", "purple"
]
Colors = Literal[
"blue",
"gray",
"red",
"yellow",
"purple",
"green",
"indigo",
"pink",
"white",
"custom",
]
SizeType = Literal["sm", "md", "lg"]
Placement = Literal["top", "bottom", "left", "right"]
@dataclass
class ActivityType:
title: str # title: Union[HTMLElement, str]
date: str # date: Union[Date, str]
src: str
alt: str
text: str = None # text: Optional[Union[HTMLElement, str]] = None
@dataclass
class AuthFieldType:
label: str
fieldtype: str
required: Optional[bool] = None
placeholder: Optional[str] = None
@dataclass
class CheckboxType:
id: str
label: str
checked: Optional[bool] = None
disabled: Optional[bool] = None
helper: Optional[str] = None
Colors = Literal[
"blue",
"gray",
"red",
"yellow",
"purple",
"green",
"indigo",
"pink",
"white",
"custom",
]
@dataclass
class DotType:
top: Optional[bool] = None
color: Optional[str] = None
DrawerTransitionTypes = Optional[
Literal[
"fade",
"fly",
"slide",
"blur",
"in:fly",
"out:fly",
"in:slide",
"out:slide",
"in:fade",
"out:fade",
"in:blur",
"out:blur",
]
]
FormColorType = Literal["blue", "red", "green", "purple", "teal", "yellow", "orange"]
Gradientduotones = Literal[
"purple2blue",
"cyan2blue",
"green2blue",
"purple2pink",
"pink2orange",
"teal2lime",
"red2yellow",
]
@dataclass
class IconType:
name: str
size: Optional[int] = None
color: Optional[Colors] = None
class_: Optional[str] = None
@dataclass
class ImgType:
src: str
alt: Optional[str] = None
InputType = Literal[
"color",
"date",
"datetime-local",
"email",
"file",
"hidden",
"image",
"month",
"number",
"password",
"reset",
"submit",
"tel",
"text",
"time",
"url",
"week",
"search",
]
@dataclass
class InteractiveTabType:
name: str
id: int
content: str
active: Optional[bool] = None
disabled: Optional[bool] = None
icon: Optional[IconType] = None
iconSize: Optional[int] = None
@dataclass
class ListGroupItemType:
current: Optional[bool] = None
disabled: Optional[bool] = None
href: Optional[str] = None
@dataclass
class LinkType:
name: str
href: Optional[str] = None
rel: Optional[str] = None
active: Optional[bool] = None
@dataclass
class ListCardType:
img: ImgType
field1: str
field2: str = ""
field3: str = ""
@dataclass
class NavbarType:
name: str
href: str
rel: str = ""
child: List["NavbarType"] = None
@dataclass
class PageType:
pageNum: number
href: str
SizeType = Literal["xs", "sm", "md", "lg", "xl"]
FormSizeType = Literal["sm", "md", "lg"]
@dataclass
class PillTabType:
name: str
selected: bool
href: str
@dataclass
class ReviewType:
name: str
imgSrc: str
imgAlt: str
title: str
rating: number
address: Optional[str] = None
reviewDate: Optional[str] = None
item1: Optional[str] = None
item2: Optional[str] = None
item3: Optional[str] = None
@dataclass
class SelectOptionType:
name: Union[str, number]
value: Union[str, number]
@dataclass
class SidebarType:
id: number
name: str
href: Optional[str] = None
# icon: Optional[Type[SvelteComponent]] = None
iconSize: Optional[number] = None
iconClass: Optional[str] = None
iconColor: Optional[str] = None
rel: Optional[str] = None
# children: Optional[List[SidebarType]] = None
# subtext: Optional[HTMLElement] = None
@dataclass
class SidebarCtaType:
label: str
# text: HTMLElement
@dataclass
class SiteType:
name: str
href: str
img: Optional[str] = None
@dataclass
class SocialMediaLinkType:
parent: str
children: Optional[List[LinkType]] = None
@dataclass
class SocialMediaType:
href: str
# icon: Type[SvelteComponent]
iconSize: Optional[number] = None
iconClass: Optional[str] = None
@dataclass
class TabHeadType:
name: str
id: number
@dataclass
class TabType:
name: str
active: bool
href: str
rel: Optional[str] = None
@dataclass
class TableDataHelperType:
start: number
end: number
total: number
@dataclass
class TimelineItemType:
date: str # date: Union[Date, str]
title: str
# icon: Optional[Type[SvelteComponent]]
href: Optional[str]
linkname: Optional[str]
text: str # text: Optional[Union[HTMLElement, str]]
@dataclass
class TimelineItemVerticalType:
date: str # date: Union[Date, str]
title: str
# icon: Optional[Type[SvelteComponent]]
iconSize: Optional[int]
iconClass: Optional[str]
href: Optional[str]
linkname: Optional[str]
text: str # text: Optional[Union[HTMLElement, str]]
@dataclass
class TimelineItemHorizontalType:
date: str # date: Union[Date, str]
title: str
# icon: Optional[Type[SvelteComponent]]
iconSize: Optional[int]
iconClass: Optional[str]
text: str # text: Optional[Union[HTMLElement, str]]
@dataclass
class TransitionParamTypes:
delay: Optional[int]
duration: Optional[int]
easing: Optional[Callable[[int], int]]
css: Optional[Callable[[int, int], str]]
tick: Optional[Callable[[int, int], None]]
Textsize = Literal[
"text-xs",
"text-sm",
"text-base",
"text-lg",
"text-xl",
"text-2xl",
"text-3xl",
"text-4xl",
]
ToggleColorType = Literal["blue", "red", "green", "purple", "yellow", "teal", "orange"]
TransitionTypes = Literal[
"fade",
"fly",
"slide",
"blur",
"in:fly",
"out:fly",
"in:slide",
"out:slide",
"in:fade",
"out:fade",
"in:blur",
"out:blur",
]
Colors = Literal[
"blue",
"gray",
"red",
"yellow",
"purple",
"green",
"indigo",
"pink",
"white",
"custom",
]
@dataclass
class drawerTransitionParamTypes:
amount: Optional[int] = None
delay: Optional[int] = None
duration: Optional[int] = None
easing: Callable = None
opacity: Optional[number] = None
x: Optional[int] = None
y: Optional[int] = None
drawerTransitionTypes = Optional[
Literal[
"fade",
"fly",
"slide",
"blur",
"in:fly",
"out:fly",
"in:slide",
"out:slide",
"in:fade",
"out:fade",
"in:blur",
"out:blur",
]
]
@dataclass
class DropdownType:
name: str
href: str
divider: Optional[bool] = None
FormColorType = Literal["blue", "red", "green", "purple", "teal", "yellow", "orange"]
Gradientduotones = Literal[
"purple2blue",
"cyan2blue",
"green2blue",
"purple2pink",
"pink2orange",
"teal2lime",
"red2yellow",
]
@dataclass
class GroupTimelineType:
title: str
src: str
alt: str
href: Optional[str] = None
isPrivate: Optional[bool] = None
comment: Optional[str] = None
@dataclass
class IconType:
name: str
size: Optional[int] = None
color: Optional[Colors] = None
class_: Optional[str] = None
@dataclass
class IconTabType:
name: str
active: bool
href: str
rel: Optional[str] = None
icon: Optional[str] = None
iconSize: Optional[int] = None
@dataclass
class ImgType:
src: str
alt: Optional[str] = None
InputType = Literal[
"color",
"date",
"datetime-local",
"email",
"file",
"hidden",
"image",
"month",
"number",
"password",
"reset",
"submit",
"tel",
"text",
"time",
"url",
"week",
"search",
]
SizeType = Literal["xs", "sm", "md", "lg", "xl"]
FormSizeType = Literal["sm", "md", "lg"]
| meerkat-main | meerkat/interactive/app/src/lib/component/flowbite/types.py |
meerkat-main | meerkat/interactive/app/src/lib/shared/__init__.py |
|
meerkat-main | meerkat/interactive/app/src/lib/shared/cell/__init__.py |
|
from meerkat.interactive.app.src.lib.component.abstract import Component
from meerkat.interactive.formatter.base import BaseFormatter
class Website(Component):
data: str
height: int
class WebsiteFormatter(BaseFormatter):
component_class: type = Website
data_prop: str = "data"
def __init__(self, height: int = 50):
super().__init__(height=height)
def _encode(self, url: str) -> str:
return url
| meerkat-main | meerkat/interactive/app/src/lib/shared/cell/website/__init__.py |
import math
import textwrap
from typing import Any
import numpy as np
import pandas as pd
from pandas.io.formats.format import format_array
from meerkat.interactive.app.src.lib.component.abstract import BaseComponent
from meerkat.interactive.formatter.base import BaseFormatter
class Scalar(BaseComponent):
data: Any
dtype: str = None
precision: int = 3
percentage: bool = False
class ScalarFormatter(BaseFormatter):
component_class: type = Scalar
data_prop: str = "data"
def __init__(self, dtype: str = None, precision: int = 3, percentage: bool = False):
super().__init__(dtype=dtype, precision=precision, percentage=percentage)
def encode(self, cell: Any):
# check for native python nan
if isinstance(cell, float) and math.isnan(cell):
return "NaN"
if isinstance(cell, np.generic):
if pd.isna(cell):
return "NaN"
return cell.item()
if hasattr(cell, "as_py"):
return cell.as_py()
return str(cell)
def html(self, cell: Any):
cell = self.encode(cell)
if isinstance(cell, str):
cell = textwrap.shorten(cell, width=100, placeholder="...")
return format_array(np.array([cell]), formatter=None)[0]
| meerkat-main | meerkat/interactive/app/src/lib/shared/cell/basic/__init__.py |
from functools import wraps
from typing import Any, Callable, List, TypeVar, cast
from meerkat.interactive.graph.marking import unmarked
from meerkat.interactive.graph.reactivity import reactive
# Used for annotating decorator usage of 'react'.
# Adapted from PyTorch:
# https://mypy.readthedocs.io/en/latest/generics.html#declaring-decorators
FuncType = Callable[..., Any]
F = TypeVar("F", bound=FuncType)
T = TypeVar("T")
_IS_MAGIC_CONTEXT: List[bool] = []
_MAGIC_FN = "magic"
def _magic(fn: Callable) -> Callable:
"""Internal decorator that is used to mark a function with a wand. Wand
functions can be activated when the magic context is active (`with
magic:`).
When the magic context is active, the function will be wrapped in
`reactive` and will be executed as a reactive function.
When the magic context is not active, the function will be effectively run
with unmarked inputs (i.e. `with unmarked():`). This means that the function
will not be added to the graph. The return value will be marked and returned.
This allows the return value to be used as a marked element in the future.
This is only meant for internal use.
with mk.unmarked():
with mk.magic():
s = s + 3 # s.__add__ is a wand
"""
def __wand(fn: Callable):
@wraps(fn)
def wrapper(*args, **kwargs):
"""Wrapper function that wraps the function in `reactive` if the
magic context is active, and just wraps with `mark` otherwise."""
# Check if magic context is active.
if is_magic_context():
# If active, we wrap with `reactive` and return.
return reactive(fn, nested_return=False)(*args, **kwargs)
else:
# Just wrap with `mark` and return.
with unmarked():
out = reactive(fn, nested_return=False)(*args, **kwargs)
# out = mark(out)
return out
# setattr(wrapper, "__wrapper__", _MAGIC_FN)
return wrapper
return __wand(fn)
class magic:
"""A context manager and decorator that changes the behavior of Store
objects inside it. All methods, properties and public attributes of Store
objects will be wrapped in @reactive decorators.
Examples:
"""
def __init__(self, magic: bool = True) -> None:
self._magic = magic
def __call__(self, func):
@wraps(func)
def decorate_context(*args, **kwargs):
with self.clone():
return func(*args, **kwargs)
setattr(decorate_context, "__wrapper__", _MAGIC_FN)
return cast(F, decorate_context)
def __enter__(self):
_IS_MAGIC_CONTEXT.append(self._magic)
return self
def __exit__(self, type, value, traceback):
_IS_MAGIC_CONTEXT.pop(-1)
def clone(self):
return self.__class__(self._magic)
def is_magic_context() -> bool:
"""Whether the code is in a magic context.
Returns:
bool: True if the code is in a magic context.
"""
# By default, we should not assume we are in a magic context.
# This will mean that Store objects will default to not decorating
# their methods and properties with @reactive.
if len(_IS_MAGIC_CONTEXT) == 0:
return False
# Otherwise, we check if the user has explicitly used the
# `magic` context manager or decorator.
return len(_IS_MAGIC_CONTEXT) > 0 and bool(_IS_MAGIC_CONTEXT[-1])
| meerkat-main | meerkat/interactive/graph/magic.py |
import logging
import warnings
from typing import Any, Generic, Iterator, List, Tuple, TypeVar, Union
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel, ValidationError
from pydantic.fields import ModelField
from wrapt import ObjectProxy
from meerkat.interactive.graph.magic import _magic, is_magic_context
from meerkat.interactive.graph.marking import is_unmarked_context, unmarked
from meerkat.interactive.graph.reactivity import reactive
from meerkat.interactive.modification import StoreModification
from meerkat.interactive.node import NodeMixin
from meerkat.interactive.types import Storeable
from meerkat.interactive.utils import get_custom_json_encoder
from meerkat.mixins.identifiable import IdentifiableMixin
from meerkat.mixins.reactifiable import MarkableMixin
__all__ = ["Store", "StoreFrontend", "make_store"]
logger = logging.getLogger(__name__)
class StoreFrontend(BaseModel):
store_id: str
value: Any
has_children: bool
is_store: bool = True
T = TypeVar("T")
# ObjectProxy must be the last base class
class Store(IdentifiableMixin, NodeMixin, MarkableMixin, Generic[T], ObjectProxy):
_self_identifiable_group: str = "stores"
# By default, stores are marked.
_self_marked = True
def __init__(self, wrapped: T, backend_only: bool = False):
super().__init__(wrapped=wrapped)
if not isinstance(self, _IteratorStore) and isinstance(wrapped, Iterator):
warnings.warn(
"Wrapping an iterator in a Store is not recommended. "
"If the iterator is derived from an iterable, wrap the iterable:\n"
" >>> store = mk.Store(iterable)\n"
" >>> iterator = iter(store)"
)
# Set up these attributes so we can create the
# schema and detail properties.
self._self_schema = None
self._self_detail = None
self._self_value = None
self._self_backend_only = backend_only
@property
def value(self):
return self.__wrapped__
def to_json(self) -> Any:
"""Converts the wrapped object into a jsonifiable object."""
return jsonable_encoder(
self.__wrapped__, custom_encoder=get_custom_json_encoder()
)
@property
def frontend(self):
return StoreFrontend(
store_id=self.id,
value=self.__wrapped__,
has_children=self.inode.has_children() if self.inode else False,
)
@property
def detail(self):
return f"Store({self.__wrapped__}) has id {self.id} and node {self.inode}"
def set(self, new_value: T) -> None:
"""Set the value of the store.
This will trigger any reactive functions that depend on this store.
Args:
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.
"""
if isinstance(new_value, Store):
# if the value is a store, then we need to unpack so it can be sent to the
# frontend
new_value = new_value.__wrapped__
logging.debug(f"Setting store {self.id}: {self.value} -> {new_value}.")
# TODO: Find operations that depend on this store and edit the cache.
# This should be done in the StoreModification
mod = StoreModification(id=self.id, value=new_value)
self.__wrapped__ = new_value
mod.add_to_queue()
@unmarked()
def __repr__(self) -> str:
return f"{type(self).__name__}({repr(self.__wrapped__)})"
def __getattr__(self, name: str) -> Any:
# This method is only run when the attribute is not found in the class.
# In this case, we will always punt the call to the wrapped object.
# Only create a reactive function if we are not in an unmarked context
# This is like creating another `getattr` function that is reactive
# and calling it with `self` as the first argument.
if is_magic_context():
@_magic
def wrapper(wrapped, name: str = name):
return getattr(wrapped, name)
# Note: this will work for both methods and properties.
return wrapper(self)
else:
# Otherwise, just return the `attr` as is.
return getattr(self.__wrapped__, name)
@classmethod
def __get_validators__(cls):
yield cls.validate
@classmethod
def validate(cls, v, field: ModelField):
if not isinstance(v, cls):
if not field.sub_fields:
# Generic parameters were not provided so we don't try to validate
# them and just return the value as is
return cls(v)
else:
# Generic parameters were provided so we try to validate them
# and return a Store object
v, error = field.sub_fields[0].validate(v, {}, loc="value")
if error:
raise ValidationError(error)
return cls(v)
return v
def __hash__(self):
return hash(self.__wrapped__)
@reactive()
def __call__(self, *args, **kwargs):
return self.__wrapped__(*args, **kwargs)
@reactive()
def __lt__(self, other):
return super().__lt__(other)
@reactive()
def __le__(self, other):
return super().__le__(other)
@reactive()
def __eq__(self, other):
return super().__eq__(other)
@reactive()
def __ne__(self, other):
return super().__ne__(other)
@reactive()
def __gt__(self, other):
return super().__gt__(other)
@reactive()
def __ge__(self, other):
return super().__ge__(other)
@_magic
def __nonzero__(self):
return super().__nonzero__()
# @reactive()
# def to_str(self):
# return super().__str__()
@reactive()
def __add__(self, other):
return super().__add__(other)
@reactive()
def __sub__(self, other):
return super().__sub__(other)
@reactive()
def __mul__(self, other):
return super().__mul__(other)
@reactive()
def __div__(self, other):
return super().__div__(other)
@reactive()
def __truediv__(self, other):
return super().__truediv__(other)
@reactive()
def __floordiv__(self, other):
return super().__floordiv__(other)
@reactive()
def __mod__(self, other):
return super().__mod__(other)
@reactive(nested_return=False)
def __divmod__(self, other):
return super().__divmod__(other)
@reactive()
def __pow__(self, other, *args):
return super().__pow__(other, *args)
@reactive()
def __lshift__(self, other):
return super().__lshift__(other)
@reactive()
def __rshift__(self, other):
return super().__rshift__(other)
@reactive()
def __and__(self, other):
return super().__and__(other)
@reactive()
def __xor__(self, other):
return super().__xor__(other)
@reactive()
def __or__(self, other):
return super().__or__(other)
@reactive()
def __radd__(self, other):
return super().__radd__(other)
@reactive()
def __rsub__(self, other):
return super().__rsub__(other)
@reactive()
def __rmul__(self, other):
return super().__rmul__(other)
@reactive()
def __rdiv__(self, other):
return super().__rdiv__(other)
@reactive()
def __rtruediv__(self, other):
return super().__rtruediv__(other)
@reactive()
def __rfloordiv__(self, other):
return super().__rfloordiv__(other)
@reactive()
def __rmod__(self, other):
return super().__rmod__(other)
@reactive()
def __rdivmod__(self, other):
return super().__rdivmod__(other)
@reactive()
def __rpow__(self, other, *args):
return super().__rpow__(other, *args)
@reactive()
def __rlshift__(self, other):
return super().__rlshift__(other)
@reactive()
def __rrshift__(self, other):
return super().__rrshift__(other)
@reactive()
def __rand__(self, other):
return super().__rand__(other)
@reactive()
def __rxor__(self, other):
return super().__rxor__(other)
@reactive()
def __ror__(self, other):
return super().__ror__(other)
@reactive()
def __neg__(self):
return super().__neg__()
@reactive()
def __pos__(self):
return super().__pos__()
@_magic
def __abs__(self):
return super().__abs__()
@reactive()
def __invert__(self):
return super().__invert__()
# We do not need to decorate i-methods because they call their
# out-of-place counterparts, which are reactive
def __iadd__(self, other):
warnings.warn(
f"{type(self).__name__}.__iadd__ is out-of-place. Use __add__ instead."
)
return self.__add__(other)
def __isub__(self, other):
warnings.warn(
f"{type(self).__name__}.__isub__ is out-of-place. Use __sub__ instead."
)
return self.__sub__(other)
def __imul__(self, other):
warnings.warn(
f"{type(self).__name__}.__imul__ is out-of-place. Use __mul__ instead."
)
return self.__mul__(other)
def __idiv__(self, other):
warnings.warn(
f"{type(self).__name__}.__idiv__ is out-of-place. Use __div__ instead."
)
return self.__div__(other)
def __itruediv__(self, other):
warnings.warn(
f"{type(self).__name__}.__itruediv__ is out-of-place. "
"Use __truediv__ instead."
)
return self.__truediv__(other)
def __ifloordiv__(self, other):
warnings.warn(
f"{type(self).__name__}.__ifloordiv__ is out-of-place. "
"Use __floordiv__ instead."
)
return self.__floordiv__(other)
def __imod__(self, other):
warnings.warn(
f"{type(self).__name__}.__imod__ is out-of-place. Use __mod__ instead."
)
return self.__mod__(other)
def __ipow__(self, other):
warnings.warn(
f"{type(self).__name__}.__ipow__ is out-of-place. Use __pow__ instead."
)
return self.__pow__(other)
def __ilshift__(self, other):
warnings.warn(
f"{type(self).__name__}.__ilshift__ is out-of-place. "
"Use __lshift__ instead."
)
return self.__lshift__(other)
def __irshift__(self, other):
warnings.warn(
f"{type(self).__name__}.__irshift__ is out-of-place. "
"Use __rshift__ instead."
)
return self.__rshift__(other)
def __iand__(self, other):
warnings.warn(
f"{type(self).__name__}.__iand__ is out-of-place. Use __and__ instead."
)
return self.__and__(other)
def __ixor__(self, other):
warnings.warn(
f"{type(self).__name__}.__ixor__ is out-of-place. Use __xor__ instead."
)
return self.__xor__(other)
def __ior__(self, other):
warnings.warn(
f"{type(self).__name__}.__ior__ is out-of-place. Use __or__ instead."
)
return self.__or__(other)
# While __index__ must return an integer, we decorate it with @reactive().
# This means that any calls to __index__ when the store is marked will
# return a Store, which will raise a TypeError.
# We do this to make sure that wrapper methods calling __index__
# handle non-integer values appropriately.
# NOTE: This only works if __index__ is always called from wrapper methods
# and the user/developer has a way of intercepting these methods or creating
# recommended practices for avoiding this error.
@reactive()
def __index__(self):
return super().__index__()
def _reactive_warning(self, name):
# If the context is not unmarked and the store is operating in a magic
# context, this method will raise a warning.
# This will primarily be done by __dunder__ methods, which are called by
# builtin Python functions (e.g. __len__ -> len, __int__ -> int, etc.)
if not is_unmarked_context() and is_magic_context():
warnings.warn(
f"Calling {name}(store) is not reactive. Use `mk.{name}(store)` to get"
f"a reactive variable (i.e. a Store). `mk.{name}(store)` behaves"
f"exactly like {name}(store) outside of this difference."
)
# Don't use @_wand on:
# - __len__
# - __int__
# - __long__
# - __float__
# - __complex__
# - __oct__
# - __hex__
# Python requires that these methods must return a primitive type
# (i.e. not a Store). As such, we cannot wrap them in @reactive using
# @_wand.
# We allow the user to call these methods on stores (e.g. len(store)),
# which will return the appropriate primitive type (i.e. not reactive).
# We raise a warning to remind the user that these methods are not reactive.
def __len__(self):
self._reactive_warning("len")
return super().__len__()
def __int__(self):
self._reactive_warning("int")
return super().__int__()
def __long__(self):
self._reactive_warning("long")
return super().__long__()
def __float__(self):
self._reactive_warning("float")
return super().__float__()
def __complex__(self):
self._reactive_warning("complex")
return super().__complex__()
def __oct__(self):
self._reactive_warning("oct")
return super().__oct__()
def __hex__(self):
self._reactive_warning("hex")
return super().__hex__()
def __bool__(self):
self._reactive_warning("bool")
return super().__bool__()
@_magic
def __contains__(self, value):
return super().__contains__(value)
@reactive(nested_return=False)
def __getitem__(self, key):
return super().__getitem__(key)
# TODO(Arjun): Check whether this needs to be reactive.
# @reactive
# def __setitem__(self, key, value):
# print("In setitem", self, "key", key, "value", value, "type", type(value))
# # Make a shallow copy of the value because this operation is not in-place.
# obj = self.__wrapped__.copy()
# obj[key] = value
# warnings.warn(f"{type(self).__name__}.__setitem__ is out-of-place.")
# return type(self)(obj, backend_only=self._self_backend_only)
@_magic
def __delitem__(self, key):
obj = self.__wrapped__.copy()
del obj[key]
warnings.warn(f"{type(self).__name__}.__delitem__ is out-of-place.")
return type(self)(obj, backend_only=self._self_backend_only)
@reactive(nested_return=False)
def __getslice__(self, i, j):
return super().__getslice__(i, j)
# # TODO(Arjun): Check whether this needs to be reactive.
# @_wand
# def __setslice__(self, i, j, value):
# obj = self.__wrapped__.copy()
# obj[i:j] = value
# warnings.warn(f"{type(self).__name__}.__setslice__ is out-of-place.")
# return type(self)(obj, backend_only=self._self_backend_only)
@_magic
def __delslice__(self, i, j):
obj = self.__wrapped__.copy()
del obj[i:j]
warnings.warn(f"{type(self).__name__}.__delslice__ is out-of-place.")
return type(self)(obj, backend_only=self._self_backend_only)
# def __enter__(self):
# return self.__wrapped__.__enter__()
# def __exit__(self, *args, **kwargs):
# return self.__wrapped__.__exit__(*args, **kwargs)
# Overriding __next__ causes issues when using Stores with third-party libraries.
# @reactive
# def __next__(self):
# return next(self.__wrapped__)
# @_wand: __iter__ behaves like a @_wand method, but cannot be decorated due to
# Pythonic limitations
@reactive()
def __iter__(self):
return iter(self.__wrapped__)
class _IteratorStore(Store):
"""A special store that wraps an iterator."""
def __init__(self, wrapped: T, backend_only: bool = False):
if not isinstance(wrapped, Iterator):
raise ValueError("wrapped object must be an Iterator.")
super().__init__(wrapped, backend_only=backend_only)
@reactive()
def __next__(self):
return next(self.__wrapped__)
def make_store(value: Union[str, Storeable]) -> Store:
"""Make a Store.
If value is a Store, return it. Otherwise, return a
new Store that wraps value.
Args:
value (Union[str, Storeable]): The value to wrap.
Returns:
Store: The Store wrapping value.
"""
return value if isinstance(value, Store) else Store(value)
def _unpack_stores_from_object(
obj: Any, unpack_nested: bool = False
) -> Tuple[Any, List[Store]]:
"""Unpack all the `Store` objects from a given object.
By default, if a store is nested inside another store,
it is not unpacked. If `unpack_nested` is True, then all stores
are unpacked.
Args:
obj: The object to unpack stores from.
unpack_nested: Whether to unpack nested stores.
Returns:
A tuple of the unpacked object and a list of the stores.
"""
# Must use no_react here so that calling a method on a `Store`
# e.g. `obj.items()` doesn't return new `Store` objects.
# Note: cannot use `no_react` as a decorator on this fn because
# it will automatically unpack the stores in the arguments.
with unmarked():
if not unpack_nested and isinstance(obj, Store):
return obj.value, [obj]
_type = type(obj)
if isinstance(obj, Store):
_type = type(obj.value)
if isinstance(obj, (list, tuple)):
stores = []
unpacked = []
for x in obj:
x, stores_i = _unpack_stores_from_object(x, unpack_nested)
unpacked.append(x)
stores.extend(stores_i)
if isinstance(obj, Store):
stores.append(obj)
return _type(unpacked), stores
elif isinstance(obj, dict):
stores = []
unpacked = {}
for k, v in obj.items():
k, stores_i_k = _unpack_stores_from_object(k, unpack_nested)
v, stores_i_v = _unpack_stores_from_object(v, unpack_nested)
unpacked[k] = v
stores.extend(stores_i_k)
stores.extend(stores_i_v)
if isinstance(obj, Store):
stores.append(obj)
return _type(unpacked), stores
elif isinstance(obj, slice):
stores = []
# TODO: Figure out if we should do unpack nested here.
start, start_store = _unpack_stores_from_object(obj.start)
stop, stop_store = _unpack_stores_from_object(obj.stop)
step, step_store = _unpack_stores_from_object(obj.step)
stores.extend(start_store)
stores.extend(stop_store)
stores.extend(step_store)
return _type(start, stop, step), stores
elif isinstance(obj, Store):
return obj.value, [obj]
else:
return obj, []
| meerkat-main | meerkat/interactive/graph/store.py |
import logging
from typing import List
from meerkat.errors import TriggerError
from meerkat.interactive.graph.marking import (
is_unmarked_context,
is_unmarked_fn,
mark,
unmarked,
)
from meerkat.interactive.graph.operation import Operation
from meerkat.interactive.graph.reactivity import is_reactive_fn, reactive
from meerkat.interactive.graph.store import Store, StoreFrontend, make_store
from meerkat.interactive.modification import Modification
from meerkat.interactive.node import _topological_sort
from meerkat.state import state
__all__ = [
"reactive",
"unmarked",
"mark",
"is_unmarked_fn",
"reactive",
"is_unmarked_context",
"is_reactive_fn",
"reactive",
"get_reactive_kwargs",
"Store",
"StoreFrontend",
"make_store",
"Operation",
"trigger",
]
logger = logging.getLogger(__name__)
@unmarked()
def trigger() -> List[Modification]:
"""Trigger the computation graph of an interface based on a list of
modifications.
To force trigger, add the modifications to the modification queue.
Return:
List[Modification]: The list of modifications that resulted from running the
computation graph.
"""
# Get all the modifications collected so far
# This clears the modification queue
modifications = state.modification_queue.clear()
# Stop tracking modifications since we're triggering with what we have
state.modification_queue.unready()
logger.debug(f"Triggering on {modifications}")
# build a graph rooted at the stores and refs in the modifications list
root_nodes = [mod.node for mod in modifications if mod.node is not None]
# Sort the nodes in topological order, and keep the Operation nodes
# TODO: dynamically traverse and sort the graph instead of pre-sorting.
# We need to do this to skip operations where inputs are not changed.
order = [
node.obj
for node in _topological_sort(root_nodes)
if isinstance(node.obj, Operation)
]
new_modifications = []
if len(order) > 0:
logger.debug(
f"Triggered pipeline: {'->'.join([node.fn.__name__ for node in order])}"
)
# Add the number of operations to the progress queue
# TODO: this should be an object that contains other information
# for the start of the progress bar
state.progress_queue.add([op.fn.__name__ for op in order])
# Go through all the operations in order: run them and add
# their modifications to the new_modifications list
for i, op in enumerate(order):
# Add the operation name to the progress queue
# TODO: this should be an object that contains other information
# for the progress bar
state.progress_queue.add(
{"op": op.fn.__name__, "progress": int(i / len(order) * 100)}
)
try:
mods = op()
except Exception as e:
# TODO (sabri): Change this to a custom error type
raise TriggerError("Exception in trigger. " + str(e)) from e
# TODO: check this
# mods = [mod for mod in mods if not isinstance(mod, StoreModification)]
new_modifications.extend(mods)
state.progress_queue.add({"op": "Done!", "progress": 100})
logger.debug("Done running trigger pipeline.")
return modifications + new_modifications
| meerkat-main | meerkat/interactive/graph/__init__.py |
import inspect
import logging
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Union
from meerkat.interactive.graph.marking import unmarked
from meerkat.interactive.graph.utils import _replace_nodes_with_nodeables
from meerkat.interactive.modification import (
DataFrameModification,
Modification,
StoreModification,
)
from meerkat.interactive.node import NodeMixin
from meerkat.interactive.types import Primitive
if TYPE_CHECKING:
from meerkat.interactive.graph.store import Store
logger = logging.getLogger(__name__)
def _check_fn_has_leading_self_arg(fn: Callable):
"""# FIXME: super hacky
# We need to figure out why Store.__eq__ (and potentially other
dunder methods) # are passed into `reactive` as the class method
instead of the instance method. # In the meantime, we can check if
the first argument is `self` and if so, # we can assume that the
function is an instance method.
"""
import inspect
parameters = list(inspect.signature(fn).parameters)
if len(parameters) > 0:
return "self" == parameters[0]
return False
class Operation(NodeMixin):
def __init__(
self,
fn: Callable,
args: List[Any],
kwargs: Dict[str, Any],
result: Any,
skip_fn: Callable[..., bool] = None,
):
super().__init__()
self.fn = fn
self.args = args
self.kwargs = kwargs
self.result = result
self.skip_fn = skip_fn
self.cache = None
if self.skip_fn is None:
self._skip_parameters = None
else:
# The fn parameters we need to extract for skip_fn.
self._skip_parameters = _validate_and_extract_skip_fn(
skip_fn=self.skip_fn, fn=self.fn
)
self._reset_cache()
def __repr__(self):
return (
f"Operation({self.fn.__name__}, {self.args}, {self.kwargs}, {self.result})"
)
def _reset_cache(self):
"""Set the cache to the new arguments and keyword arguments."""
args, kwargs = self._dereference_nodes()
cache = inspect.getcallargs(self.fn, *args, **kwargs)
self.cache = {param: cache[param] for param in self._skip_parameters}
def _run_skip_fn(self, *args, **kwargs):
"""Run the skip_fn to determine if the operation should be skipped.
Args:
*args: The new arguments to the function.
**kwargs: The new keyword arguments to the function.
"""
# Process cache.
skip_kwargs = {f"old_{k}": v for k, v in self.cache.items()}
self.cache = {}
# Process new arguments.
new_kwargs = inspect.getcallargs(self.fn, *args, **kwargs)
new_kwargs = {
f"new_{param}": new_kwargs[param] for param in self._skip_parameters
}
skip_kwargs.update(new_kwargs)
skip = self.skip_fn(**skip_kwargs)
logger.debug(f"Operation({self.fn.__name__}): skip_fn -> {skip}")
return skip
def _dereference_nodes(self):
# Dereference the nodes.
args = _replace_nodes_with_nodeables(self.args, unwrap_stores=True)
kwargs = _replace_nodes_with_nodeables(self.kwargs, unwrap_stores=True)
# Special logic to make sure we unwrap all Store objects, except those
# that correspond to `self`.
if _check_fn_has_leading_self_arg(self.fn):
args = list(args)
args[0] = _replace_nodes_with_nodeables(self.args[0], unwrap_stores=False)
return args, kwargs
def __call__(self) -> List[Modification]:
"""Execute the operation. Unpack the arguments and keyword arguments
and call the function. Then, update the result Reference with the
result and return a list of modifications.
These modifications describe the delta changes made to the
result Reference, and are used to update the state of the GUI.
"""
logger.debug(f"Running {repr(self)}")
# Dereference the nodes.
args, kwargs = self._dereference_nodes()
# If we are skipping the function, then we can
# return an empty list of modifications.
if self.skip_fn is not None:
skip = self._run_skip_fn(*args, **kwargs)
# Reset the cache to the new arguments and keyword arguments.
# FIXME: We are deferencing the nodes again, which we dont need to do.
self._reset_cache()
if skip:
return []
with unmarked():
update = self.fn(*args, **kwargs)
modifications = []
self.result = _update_result(self.result, update, modifications=modifications)
return modifications
def _update_result(
result: Union[list, tuple, dict, "Store", Primitive],
update: Union[list, tuple, dict, "Store", Primitive],
modifications: List[Modification],
) -> Union[list, tuple, dict, "Store", Primitive]:
"""Update the result object with the update object. This recursive function
will perform a nested update to the result with the update. This function
will also update the modifications list with the changes made to the result
object.
Args:
result: The result object to update.
update: The update object to use to update the result.
modifications: The list of modifications to update.
Returns:
The updated result object.
"""
from meerkat.dataframe import DataFrame
from meerkat.interactive.graph.store import Store
from meerkat.interactive.utils import is_equal
if isinstance(result, DataFrame):
# Detach the result object from the Node
inode = result.detach_inode()
# Attach the inode to the update object
update.attach_to_inode(inode)
# Create modifications
modifications.append(DataFrameModification(id=inode.id, scope=update.columns))
return update
elif isinstance(result, Store):
# If the result is a Store, then we need to update the Store's value
# and return a StoreModification
# TODO(karan): now checking if the value is the same
# This is assuming that all values put into Stores have an __eq__ method
# defined that can be used to check if the value has changed.
if isinstance(result, (str, int, float, bool, type(None), tuple)):
# We can just check if the value is the same
if not is_equal(result.value, update):
result.set(update)
modifications.append(
StoreModification(id=result.inode.id, value=update)
)
else:
# We can't just check if the value is the same if the Store contains
# a list, dict or object, since they are mutable (and it would just
# return True).
result.set(update)
modifications.append(StoreModification(id=result.inode.id, value=update))
return result
elif isinstance(result, list):
# Recursively update each element of the list
return [_update_result(r, u, modifications) for r, u in zip(result, update)]
elif isinstance(result, tuple):
# Recursively update each element of the tuple
return tuple(
_update_result(r, u, modifications) for r, u in zip(result, update)
)
elif isinstance(result, dict):
# Recursively update each element of the dict
return {
k: _update_result(v, update[k], modifications) for k, v in result.items()
}
else:
# If the result is not a Reference or Store, then it is a primitive type
# and we can just return the update
return update
def _validate_and_extract_skip_fn(*, skip_fn, fn) -> set:
# Skip functions should have arguments that start with `old_` and `new_`
# followed by the same keyword argument name.
# e.g. def skip(old_x, new_x):
fn_parameters = inspect.signature(fn).parameters.keys()
skip_parameters = inspect.signature(skip_fn).parameters.keys()
if not all(
param.startswith("old_") or param.startswith("new_")
for param in skip_parameters
):
raise ValueError(
f"Expected skip_fn to have parameters that start with "
f"`old_` or `new_`, but got parameters: {skip_parameters}"
)
# Remove the `old_` and `new_` prefixes from the skip parameters.
skip_parameters_no_prefix = {param[4:] for param in skip_parameters}
if not skip_parameters_no_prefix.issubset(fn_parameters):
unknown_parameters = skip_parameters_no_prefix - fn_parameters
unknown_parameters = [x for x in skip_parameters if x[4:] in unknown_parameters]
unknown_parameters = ", ".join(unknown_parameters)
raise ValueError(
"Expected skip_fn to have parameters that match the "
"parameters of the function, but got parameters: "
f"{skip_parameters_no_prefix}"
)
return skip_parameters_no_prefix
| meerkat-main | meerkat/interactive/graph/operation.py |
from typing import List
from meerkat.interactive.node import Node, NodeMixin
def _replace_nodeables_with_nodes(obj):
if isinstance(obj, NodeMixin):
obj = obj.inode
elif isinstance(obj, list) or isinstance(obj, tuple):
obj = type(obj)(_replace_nodeables_with_nodes(x) for x in obj)
elif isinstance(obj, dict):
obj = {
_replace_nodeables_with_nodes(k): _replace_nodeables_with_nodes(v)
for k, v in obj.items()
}
return obj
def _replace_nodes_with_nodeables(obj, unwrap_stores=True):
from meerkat.interactive.graph.store import Store
if isinstance(obj, Node):
obj = obj.obj
if unwrap_stores:
# Replace `Store` objects with their wrapped values
if isinstance(obj, Store):
obj = obj.__wrapped__
elif isinstance(obj, list) or isinstance(obj, tuple):
obj = type(obj)(_replace_nodes_with_nodeables(x) for x in obj)
elif isinstance(obj, dict):
obj = {
_replace_nodes_with_nodeables(k): _replace_nodes_with_nodeables(v)
for k, v in obj.items()
}
return obj
def _get_nodeables(*args, **kwargs) -> List[NodeMixin]:
# TODO: figure out if we need to handle this case
# Store([Store(1), Store(2), Store(3)])
nodeables = []
for arg in args:
if isinstance(arg, NodeMixin):
nodeables.append(arg)
elif isinstance(arg, list) or isinstance(arg, tuple):
nodeables.extend(_get_nodeables(*arg))
elif isinstance(arg, dict):
nodeables.extend(_get_nodeables(**arg))
elif isinstance(arg, slice):
nodeables.extend(_get_nodeables(arg.start, arg.stop, arg.step))
for _, v in kwargs.items():
if isinstance(v, NodeMixin):
nodeables.append(v)
elif isinstance(v, list) or isinstance(v, tuple):
nodeables.extend(_get_nodeables(*v))
elif isinstance(v, dict):
nodeables.extend(_get_nodeables(**v))
elif isinstance(v, slice):
nodeables.extend(_get_nodeables(arg.start, arg.stop, arg.step))
return nodeables
| meerkat-main | meerkat/interactive/graph/utils.py |
from functools import wraps
from typing import Any, Callable, List, TypeVar, cast
# Used for annotating decorator usage of 'react'.
# Adapted from PyTorch:
# https://mypy.readthedocs.io/en/latest/generics.html#declaring-decorators
FuncType = Callable[..., Any]
F = TypeVar("F", bound=FuncType)
T = TypeVar("T")
_IS_UNMARKED_CONTEXT: List[bool] = []
_UNMARKED_FN = "unmarked"
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.
"""
def __call__(self, func):
from meerkat.interactive.graph.reactivity import reactive
@wraps(func)
def decorate_context(*args, **kwargs):
with self.clone():
return reactive(func, nested_return=False)(*args, **kwargs)
setattr(decorate_context, "__wrapper__", _UNMARKED_FN)
return cast(F, decorate_context)
def __enter__(self):
_IS_UNMARKED_CONTEXT.append(True)
return self
def __exit__(self, type, value, traceback):
_IS_UNMARKED_CONTEXT.pop(-1)
def clone(self):
return self.__class__()
def is_unmarked_context() -> bool:
"""Whether the code is in an unmarked context.
Returns:
bool: True if the code is in an unmarked context.
"""
# By default, we should not assume we are in an unmarked context.
# This will allow functions that are decorated with `reactive` to
# add nodes to the graph.
if len(_IS_UNMARKED_CONTEXT) == 0:
return False
# TODO: we need to check this since users are only allowed the use
# of the `unmarked` context manager. Therefore, everything is reactive
# by default, *unless the user has explicitly used `unmarked`*.
return len(_IS_UNMARKED_CONTEXT) > 0 and bool(_IS_UNMARKED_CONTEXT[-1])
def is_unmarked_fn(fn: Callable) -> bool:
"""Check if a function is wrapped by the `unmarked` decorator."""
return (
hasattr(fn, "__wrapped__")
and hasattr(fn, "__wrapper__")
and fn.__wrapper__ == _UNMARKED_FN
)
def mark(input: T) -> 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.
Args:
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)
"""
from meerkat.interactive.graph.store import Store
from meerkat.mixins.reactifiable import MarkableMixin
if isinstance(input, MarkableMixin):
return input.mark()
return Store(input)
| meerkat-main | meerkat/interactive/graph/marking.py |
import types
from functools import partial, wraps
from typing import Callable, Iterator
from meerkat.interactive.graph.marking import is_unmarked_context, unmarked
from meerkat.interactive.graph.operation import (
Operation,
_check_fn_has_leading_self_arg,
)
from meerkat.interactive.graph.utils import (
_get_nodeables,
_replace_nodeables_with_nodes,
)
from meerkat.interactive.node import NodeMixin
from meerkat.mixins.reactifiable import MarkableMixin
__all__ = ["reactive", "reactive", "is_unmarked_context"]
_REACTIVE_FN = "reactive"
def isclassmethod(method):
"""
StackOverflow: https://stackoverflow.com/a/19228282
"""
bound_to = getattr(method, "__self__", None)
if not isinstance(bound_to, type):
# must be bound to a class
return False
name = method.__name__
for cls in bound_to.__mro__:
descriptor = vars(cls).get(name)
if descriptor is not None:
return isinstance(descriptor, classmethod)
return False
def reactive(
fn: Callable = None,
nested_return: bool = False,
skip_fn: 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
:func:`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:
.. code-block:: python
@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:
.. code-block:: python
@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)
Args:
fn: See :func:`react`.
nested_return: See :func:`react`.
skip_fn: See :func:`react`.
Returns:
See :func:`react`.
"""
# TODO: Remove nested_return argument. With the addition of __iter__ and __next__
# to mk.Store, we no longer need to support nested return values.
# This will require looking through current use of reactive and patching them.
if fn is None:
# need to make passing args to the args optional
# note: all of the args passed to the decorator MUST be optional
return partial(
reactive,
nested_return=nested_return,
skip_fn=skip_fn,
backend_only=backend_only,
)
# Built-in functions cannot be wrapped in reactive.
# They have to be converted to a lambda function first and then run.
if isinstance(fn, types.BuiltinFunctionType):
raise ValueError(
"Cannot wrap built-in function in reactive. "
"Please convert to lambda function first:\n"
" >>> reactive(lambda x: {}(x))".format(fn.__name__)
)
def __reactive(fn: Callable):
@wraps(fn)
def wrapper(*args, **kwargs):
"""This `wrapper` function is only run once. It creates a node in
the operation graph and returns a `Reference` object that wraps the
output of the function.
Subsequent calls to the function will be handled by the
graph.
"""
from meerkat.interactive.graph.store import (
Store,
_IteratorStore,
_unpack_stores_from_object,
)
# nested_return is False because any operations on the outputs of the
# function should recursively generate Stores / References.
# For example, if fn returns a list. The reactified fn will return
# a Store(list).
# Then, Store(list)[0] should also return a Store.
# TODO (arjun): These if this assumption holds.
nonlocal nested_return
nonlocal backend_only
nonlocal fn
_is_unmarked_context = is_unmarked_context()
# Check if fn is a bound method (i.e. an instance method).
# If so, we need to functionalize the method (i.e. make the method
# into a function).
# First argument in *args must be the instance.
# We assume that the type of the instance will not change.
def _fn_outer_wrapper(_fn):
@wraps(_fn)
def _fn_wrapper(*args, **kwargs):
return _fn(*args, **kwargs)
return _fn_wrapper
# Unpack the stores from the args and kwargs
unpacked_args, _ = _unpack_stores_from_object(list(args))
unpacked_kwargs, _ = _unpack_stores_from_object(kwargs)
_force_no_react = False
if hasattr(fn, "__self__") and fn.__self__ is not None:
if isclassmethod(fn):
# If the function is a classmethod, then it will always be
# bound to the class when we grab it later in this block,
# and we don't need to unpack the first argument.
args = args
else:
args = (fn.__self__, *args)
# Unpack the stores from the args and kwargs because
# args has changed!
# TODO: make this all nicer
unpacked_args, _ = _unpack_stores_from_object(list(args))
unpacked_kwargs, _ = _unpack_stores_from_object(kwargs)
# The method bound to the class.
try:
fn_class = getattr(fn.__self__.__class__, fn.__name__)
except AttributeError:
fn_class = getattr(fn.__self__.mro()[0], fn.__name__)
fn = _fn_outer_wrapper(fn_class)
# If `fn` is an instance method, then the first argument in `args`
# is the instance. We should **not** unpack the `self` argument
# if it is a Store.
if args and isinstance(args[0], Store):
unpacked_args[0] = args[0]
elif _check_fn_has_leading_self_arg(fn):
# If the object is a MarkableMixin and fn has a leading self arg,
# (i.e. fn(self, ...)), then we need to check if the function
# should be added to the graph.
# If the object is a MarkableMixin, the fn will be added
# to the graph only when the object is marked (i.e. `obj.marked`).
# This is required for magic methods for MarkableMixin instances
# because shorthand accessors (e.g. x[0] for x.__getitem__(0)) do not
# use the __getattribute__ method.
# TODO: When the function is an instance method, should
# instance.marked determine if the function is reactive?
# obj = args[0]
# if isinstance(obj, MarkableMixin):
# with unmarked():
# is_obj_reactive = obj.marked
# _force_no_react = not is_obj_reactive
# If `fn` is an instance method, then the first argument in `args`
# is the instance. We should **not** unpack the `self` argument
# if it is a Store.
if isinstance(args[0], Store):
unpacked_args[0] = args[0]
# We need to check the arguments to see if they are reactive.
# If any of the inputs into fn are reactive, we need to add fn
# to the graph.
with unmarked():
any_inputs_marked = _any_inputs_marked(*args, **kwargs)
# Call the function on the args and kwargs
with unmarked():
result = fn(*unpacked_args, **unpacked_kwargs)
# TODO: Check if result is equal to one of the inputs.
# If it is, we need to copy it.
if _is_unmarked_context or _force_no_react or not any_inputs_marked:
# If we are in an unmarked context, then we don't need to create
# any nodes in the graph.
# `fn` should be run as normal.
return result
# Now we're in a reactive context i.e. is_reactive() == True
# Get all the NodeMixin objects from the args and kwargs.
# These objects will be parents of the Operation node
# that is created for this function.
nodeables = _get_nodeables(*args, **kwargs)
# Wrap the Result in NodeMixin objects
if nested_return:
result = _nested_apply(
result, fn=partial(_wrap_outputs, backend_only=backend_only)
)
elif isinstance(result, NodeMixin):
result = result
elif isinstance(result, Iterator):
result = _IteratorStore(result, backend_only=backend_only)
else:
result = Store(result, backend_only=backend_only)
# If the object is a ReactifiableMixin, we should turn
# reactivity on.
# TODO: This should be done in a nested way.
if isinstance(result, MarkableMixin):
result._self_marked = True
with unmarked():
# Setup an Operation node if any of the args or kwargs
# were nodeables
op = None
# Create Nodes for each NodeMixin object
_create_nodes_for_nodeables(*nodeables)
args = _replace_nodeables_with_nodes(args)
kwargs = _replace_nodeables_with_nodes(kwargs)
# Create the Operation node
op = Operation(
fn=fn,
args=args,
kwargs=kwargs,
result=result,
skip_fn=skip_fn,
)
# For normal functions
# Make a node for the operation if it doesn't have one
if not op.has_inode():
op.attach_to_inode(op.create_inode())
# Add this Operation node as a child of all of the nodeables.
# This function takes care of only adding it as a child for
# nodeables that are marked.
_add_op_as_child(op, *nodeables)
# Attach the Operation node to its children (if it is not None)
def _foo(nodeable: NodeMixin):
# FIXME: make sure they are not returning a nodeable that
# is already in the dag. May be related to checking that the graph
# is acyclic.
if not nodeable.has_inode():
inode_id = (
None if not isinstance(nodeable, Store) else nodeable.id
)
nodeable.attach_to_inode(
nodeable.create_inode(inode_id=inode_id)
)
if op is not None:
op.inode.add_child(nodeable.inode)
_nested_apply(result, _foo)
return result
setattr(wrapper, "__wrapper__", _REACTIVE_FN)
return wrapper
return __reactive(fn)
def is_reactive_fn(fn: Callable) -> bool:
"""Check if a function is wrapped by the `reactive` decorator."""
return (
hasattr(fn, "__wrapped__")
and hasattr(fn, "__wrapper__")
and fn.__wrapper__ == _REACTIVE_FN
)
def _nested_apply(obj: object, fn: Callable):
from meerkat.interactive.graph.store import Store
def _internal(_obj: object, depth: int = 0):
if isinstance(_obj, Store) or isinstance(_obj, NodeMixin):
return fn(_obj)
if isinstance(_obj, list):
return [_internal(v, depth=depth + 1) for v in _obj]
elif isinstance(_obj, tuple):
return tuple(_internal(v, depth=depth + 1) for v in _obj)
elif isinstance(_obj, dict):
return {k: _internal(v, depth=depth + 1) for k, v in _obj.items()}
elif _obj is None:
return None
elif depth > 0:
# We want to call the function on the object (including primitives) when we
# have recursed into it at least once.
return fn(_obj)
else:
raise ValueError(f"Unexpected type {type(_obj)}.")
return _internal(obj)
def _add_op_as_child(op: Operation, *nodeables: NodeMixin):
"""Add the operation as a child of the nodeables.
Args:
op: The operation to add as a child.
nodeables: The nodeables to add the operation as a child.
"""
for nodeable in nodeables:
# Add the operation as a child of the nodeable
triggers = nodeable.marked if isinstance(nodeable, MarkableMixin) else True
nodeable.inode.add_child(op.inode, triggers=triggers)
def _wrap_outputs(obj, backend_only=False):
from meerkat.interactive.graph.store import Store, _IteratorStore
if isinstance(obj, NodeMixin):
return obj
elif isinstance(obj, Iterator):
return _IteratorStore(obj, backend_only=backend_only)
return Store(obj, backend_only=backend_only)
def _create_nodes_for_nodeables(*nodeables: NodeMixin):
from meerkat.interactive.graph.store import Store
for nodeable in nodeables:
assert isinstance(nodeable, NodeMixin)
# Make a node for this nodeable if it doesn't have one
if not nodeable.has_inode():
inode_id = None if not isinstance(nodeable, Store) else nodeable.id
nodeable.attach_to_inode(nodeable.create_inode(inode_id=inode_id))
def _any_inputs_marked(*args, **kwargs) -> bool:
"""Returns True if any of the inputs are reactive.
Note: This function does not recursively check the arguments for
reactive inputs.
"""
def _is_marked(obj):
return isinstance(obj, MarkableMixin) and obj.marked
return any(_is_marked(arg) for arg in args) or any(
_is_marked(arg) for arg in kwargs.values()
)
| meerkat-main | meerkat/interactive/graph/reactivity.py |
from ..app.src.lib.component.core.icon import Icon
from .base import Formatter
class IconFormatter(Formatter):
component_class = Icon
data_prop: str = "data"
static_encode: bool = True
def encode(self, data: str) -> str:
return ""
| meerkat-main | meerkat/interactive/formatter/icon.py |
from typing import Any, Dict, List, Tuple
import numpy as np
from PIL import Image as PILImage
from scipy.ndimage import zoom
from meerkat import env
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, endpoint
from meerkat.interactive.formatter.icon import IconFormatter
from ..app.src.lib.component.core.medimage import MedicalImage
from .base import DeferredFormatter, FormatterGroup
from .image import ImageFormatter
if env.package_available("voxel"):
import voxel as vx
from voxel import MedicalVolume
else:
MedicalVolume = None
class MedicalImageFormatter(ImageFormatter):
component_class = MedicalImage
data_prop: str = "data"
def __init__(
self,
max_size: Tuple[int] = None,
classes: str = "",
dim: int = 2,
scrollable: bool = False,
show_toolbar: bool = False,
type: str = "image",
segmentation_column: str = "",
):
if not env.package_available("voxel"):
raise ImportError(
"voxel is not installed. Install with `pip install pyvoxel`."
)
if not self._is_valid_type(type):
raise ValueError(
f"Unknown type '{type}'. Expected ['image', 'segmentation']."
)
super().__init__(max_size=max_size, classes=classes)
self.dim = dim
self.scrollable = scrollable
self.show_toolbar = show_toolbar
self.type = type
self.segmentation_column = segmentation_column
self._fetch_data: Endpoint = self.fetch_data.partial(self)
def encode(
self,
cell: MedicalVolume,
*,
skip_copy: bool = False,
dim: int = None,
type: str = None,
) -> List[str]:
"""Encodes an image as a base64 string.
Args:
cell: The image to encode.
dim: The dimension to slice along.
"""
from meerkat.columns.deferred.base import DeferredCell
if type is None:
type = self.type
if not self._is_valid_type(type):
raise ValueError(
f"Unknown type '{type}'. Expected ['image', 'segmentation']."
)
if isinstance(cell, DeferredCell):
cell = cell()
return self.encode(cell, skip_copy=skip_copy, dim=dim, type=type)
if dim is None:
dim = self.dim
if isinstance(dim, str):
dim = cell.orientation.index(dim)
if not self.scrollable:
# TODO: Update when np.take supported in voxel.
length = cell.shape[dim]
sl = slice(length // 2, length // 2 + 1)
sls = [slice(None), slice(None), slice(None)]
sls[dim] = sl
cell = cell[tuple(sls)]
cell: MedicalVolume = cell.materialize()
breakpoint
if type == "image":
return self._process_image(cell, dim)
elif type == "segmentation":
return self._process_segmentation(cell, dim)
def _is_valid_type(self, type):
return type in ["image", "segmentation"]
def _process_image(self, cell, dim: int):
cell = cell.apply_window(inplace=False)
cell = self._resize(cell, slice_dim=dim)
# Put the slice dimension first.
arr = cell.volume
arr = np.transpose(arr, (dim, *range(dim), *(range(dim + 1, cell.ndim))))
# Normalize the array to [0, 255] uint8.
arr = arr - arr.min()
arr = np.clip(arr, 0, np.percentile(arr, 98))
arr: np.ndarray = np.round(arr / arr.max() * 255)
arr = arr.astype(np.uint8)
arr_slices = [arr[i] for i in range(arr.shape[0])]
# TODO: Investigate why we need to pass MedicalImageFormatter to super.
return [super(MedicalImageFormatter, self).encode(x) for x in arr_slices]
def _process_segmentation(self, cell, dim: int):
# We assume the segmentation is one-hot encoded.
arr: np.ndarray = cell.volume
# Resize the image to match resolution.
zoom_extent = self._get_zoom_extent(cell, dim)
# Resize the image to max size.
if self.max_size:
inplane_dims = [i for i in range(3) if i != dim]
inplane_shape = np.asarray([cell.shape[i] for i in inplane_dims])
downsample_factor = np.max(inplane_shape / np.asarray(self.max_size))
for _dim in inplane_dims:
zoom_extent[_dim] /= downsample_factor
# Zoom into the array (if necessary).
if not np.allclose(zoom_extent, 1.0):
arr = zoom(arr, zoom_extent)
# Threshold the zoomed image.
arr = arr > 0.5
arr = arr.astype(bool)
# Colorize the image.
arr = _colorize(arr)
# Convert to 2D slices.
arr = np.transpose(arr, (dim, *range(dim), *(range(dim + 1, cell.ndim))))
arr_slices = [PILImage.fromarray(arr[i]) for i in range(arr.shape[0])]
return [
super(MedicalImageFormatter, self).encode(x, mode="RGBA")
for x in arr_slices
]
def _get_zoom_extent(self, mv: MedicalVolume, slice_dim: int) -> MedicalVolume:
spacing = np.asarray(mv.pixel_spacing)
inplane_dims = [i for i in range(3) if i != slice_dim]
inplane_spacing = np.asarray([spacing[dim] for dim in inplane_dims])
zoom_extent = np.ones(2)
# Resize for pixel spacing.
if np.allclose(inplane_spacing, inplane_spacing[0]):
return np.ones(mv.ndim)
resolution = np.max(inplane_spacing)
zoom_extent *= inplane_spacing / resolution
total_zoom_extent = np.ones(mv.ndim)
for i, dim in enumerate(inplane_dims):
total_zoom_extent[dim] = zoom_extent[i]
return total_zoom_extent
def _resize(self, mv: MedicalVolume, slice_dim: int) -> MedicalVolume:
"""Resizes a medical volume so that in-plane is the same resolution (in
mm).
Args:
mv: The medical volume to resize.
slice_dim: The dimension to slice along.
"""
spacing = np.asarray(mv.pixel_spacing)
zoom_extent = self._get_zoom_extent(mv, slice_dim=slice_dim)
if np.allclose(zoom_extent, 1.0):
return mv
arr = zoom(mv.volume, zoom_extent)
return MedicalVolume(arr, vx.to_affine(mv.orientation, spacing))
@endpoint()
def fetch_data(
self,
df: DataFrame,
column: str,
index: int,
dim: int = None,
type: str = "image",
) -> List[str]:
cell = df[column][index]
return self.encode(cell, dim=dim, type=type)
@property
def props(self) -> Dict[str, Any]:
return {
"classes": self.classes,
"show_toolbar": self.show_toolbar,
"on_fetch": self._fetch_data.frontend,
"dim": self.dim,
"segmentation_column": self.segmentation_column,
}
def html(self, cell: MedicalVolume) -> str:
# TODO: Fix standard html rendering.
encoded = self.encode(cell)
return f'<img src="{encoded[len(encoded) // 2]}">'
def _get_state(self) -> Dict[str, Any]:
return {
"max_size": self.max_size,
"classes": self.classes,
"dim": self.dim,
"show_toolbar": self.show_toolbar,
}
def _set_state(self, state: Dict[str, Any]):
self.max_size = state["max_size"]
self.classes = state["classes"]
self.dim = state["dim"]
self.show_toolbar = state["show_toolbar"]
class MedicalImageFormatterGroup(FormatterGroup):
formatter_class: type = MedicalImageFormatter
def __init__(self, classes: str = "", dim: int = None, type: str = None):
super().__init__(
icon=IconFormatter(name="Image"),
base=self.formatter_class(classes=classes),
tiny=self.formatter_class(max_size=[32, 32], classes=classes),
small=self.formatter_class(max_size=[64, 64], classes=classes),
thumbnail=self.formatter_class(max_size=[256, 256], classes=classes),
gallery=self.formatter_class(
max_size=[512, 512],
classes="h-full w-full" + " " + classes,
),
full=self.formatter_class(
classes=classes, scrollable=True, show_toolbar=True
),
)
if dim is not None:
self.dim = dim
if type is not None:
self.type = type
@property
def dim(self):
return self["base"].dim
@dim.setter
def dim(self, value):
for v in self._dict.values():
v = _get_wrapped_formatter(v)
if isinstance(v, MedicalImageFormatter):
v.dim = value
@property
def type(self):
return self["base"].type
@type.setter
def type(self, value):
for v in self._dict.values():
v = _get_wrapped_formatter(v)
if isinstance(v, MedicalImageFormatter):
v.type = value
if value == "segmentation":
self._dict["tiny"] = IconFormatter(name="Image")
@property
def segmentation_column(self):
return self["base"].segmentation_column
@segmentation_column.setter
def segmentation_column(self, value):
for v in self._dict.values():
v = _get_wrapped_formatter(v)
if isinstance(v, MedicalImageFormatter):
v.segmentation_column = value
def _get_wrapped_formatter(formatter):
if isinstance(formatter, DeferredFormatter):
return _get_wrapped_formatter(formatter.wrapped)
return formatter
def _colorize(x: np.ndarray):
"""Colorize the segmentation array.
Args:
x: An array representing the segmentation (..., num_classes)
Returns:
An array of shape (..., 4) where the last dimension is RGBA.
"""
arr = np.zeros(x.shape[:-1] + (4,), dtype=np.uint8)
num_classes = x.shape[-1]
for k in range(num_classes):
arr[x[..., k]] = np.asarray(_COLORS[k] + (255,))
return arr
_COLORS = [
(255, 0, 0),
(0, 255, 0),
(0, 0, 255),
(255, 255, 0),
(255, 0, 255),
(0, 255, 255),
(128, 128, 128),
(255, 128, 0),
(128, 0, 128),
(0, 128, 128),
]
| meerkat-main | meerkat/interactive/formatter/medimage.py |
import math
import textwrap
from typing import Any, Dict
import numpy as np
import pandas as pd
from pandas.io.formats.format import format_array
from meerkat.interactive.app.src.lib.component.core.number import Number
from meerkat.interactive.formatter.base import BaseFormatter, FormatterGroup
from meerkat.interactive.formatter.icon import IconFormatter
class NumberFormatter(BaseFormatter):
component_class: type = Number
data_prop: str = "data"
def __init__(
self,
dtype: str = "auto",
precision: int = 3,
percentage: bool = False,
classes: str = "",
):
self.dtype = dtype
self.precision = precision
self.percentage = percentage
self.classes = classes
@property
def props(self):
return {
"dtype": self.dtype,
"precision": self.precision,
"percentage": self.percentage,
"classes": self.classes,
}
def encode(self, cell: Any):
# check for native python nan
if isinstance(cell, float) and math.isnan(cell):
return "NaN"
if isinstance(cell, (str, int, float)):
return cell
if isinstance(cell, np.generic):
if pd.isna(cell):
return "NaN"
return cell.item()
if hasattr(cell, "as_py"):
return cell.as_py()
return str(cell)
def html(self, cell: Any):
cell = self.encode(cell)
if isinstance(cell, str):
cell = textwrap.shorten(cell, width=100, placeholder="...")
return format_array(np.array([cell]), formatter=None)[0]
def _get_state(self) -> Dict[str, Any]:
return {
"dtype": self.dtype,
"precision": self.precision,
"percentage": self.percentage,
"classes": self.classes,
}
def _set_state(self, state: Dict[str, Any]):
self.dtype = state["dtype"]
self.precision = state["precision"]
self.percentage = state["percentage"]
self.classes = state["classes"]
class NumberFormatterGroup(FormatterGroup):
def __init__(self, **kwargs):
super().__init__(
base=NumberFormatter(**kwargs), icon=IconFormatter(name="Hash")
)
| meerkat-main | meerkat/interactive/formatter/number.py |
from ..app.src.lib.component.core.raw_html import RawHTML
from .base import Formatter, FormatterGroup
from .icon import IconFormatter
class HTMLFormatter(Formatter):
component_class: type = RawHTML
data_prop: str = "html"
def encode(self, data: str) -> str:
return data
def html(self, cell: str) -> str:
return "HTML"
class HTMLFormatterGroup(FormatterGroup):
def __init__(self, sanitize: bool = True, classes: str = ""):
super().__init__(
base=HTMLFormatter(view="full", sanitize=sanitize, classes=classes),
icon=IconFormatter(name="Globe2"),
tag=IconFormatter(name="Globe2"),
thumbnail=HTMLFormatter(
view="thumbnail", sanitize=sanitize, classes=classes
),
gallery=HTMLFormatter(view="thumbnail", sanitize=sanitize, classes=classes),
)
| meerkat-main | meerkat/interactive/formatter/raw_html.py |
from ..app.src.lib.component.core.code import Code
from .base import Formatter, FormatterGroup
from .icon import IconFormatter
class CodeFormatter(Formatter):
component_class = Code
data_prop: str = "body"
class CodeFormatterGroup(FormatterGroup):
def __init__(self):
super().__init__(
base=CodeFormatter(),
icon=IconFormatter(name="CodeSquare"),
tiny=IconFormatter(name="CodeSquare"),
tag=IconFormatter(name="CodeSquare"),
thumbnail=CodeFormatter(),
gallery=CodeFormatter(classes="h-full aspect-[3/4]"),
full=CodeFormatter(classes="h-full w-ful rounded-lg"),
)
| meerkat-main | meerkat/interactive/formatter/code.py |
from .audio import AudioFormatter, AudioFormatterGroup
from .base import Formatter, deferred_formatter_group
from .boolean import BooleanFormatter, BooleanFormatterGroup
from .code import CodeFormatter, CodeFormatterGroup
from .image import (
DeferredImageFormatter,
DeferredImageFormatterGroup,
ImageFormatter,
ImageFormatterGroup,
)
from .medimage import MedicalImageFormatter, MedicalImageFormatterGroup
from .number import NumberFormatter, NumberFormatterGroup
from .pdf import PDFFormatter, PDFFormatterGroup
from .raw_html import HTMLFormatter, HTMLFormatterGroup
from .tensor import TensorFormatter, TensorFormatterGroup
from .text import TextFormatter, TextFormatterGroup
__all__ = [
"Formatter",
"deferred_formatter_group",
"ImageFormatter",
"ImageFormatterGroup",
"DeferredImageFormatter",
"DeferredImageFormatterGroup",
"TextFormatter",
"TextFormatterGroup",
"NumberFormatter",
"NumberFormatterGroup",
"HTMLFormatter",
"HTMLFormatterGroup",
"CodeFormatter",
"CodeFormatterGroup",
"PDFFormatter",
"PDFFormatterGroup",
"TensorFormatter",
"TensorFormatterGroup",
"BooleanFormatter",
"BooleanFormatterGroup",
"AudioFormatter",
"AudioFormatterGroup",
"MedicalImageFormatter",
"MedicalImageFormatterGroup",
]
# backwards compatibility
class DeprecatedFormatter: # noqa: E302
pass
ObjectFormatter = DeprecatedFormatter
BasicFormatter = DeprecatedFormatter
NumpyArrayFormatter = DeprecatedFormatter
# TensorFormatter = DeprecatedFormatter
WebsiteFormatter = DeprecatedFormatter
# CodeFormatter = DeprecatedFormatter
PILImageFormatter = DeprecatedFormatter
| meerkat-main | meerkat/interactive/formatter/__init__.py |
from ..app.src.lib.component.core.pdf import PDF
from .base import Formatter, FormatterGroup
from .icon import IconFormatter
class PDFFormatter(Formatter):
component_class: type = PDF
data_prop: str = "data"
def encode(self, data: bytes) -> str:
return data.decode("latin-1")
class PDFFormatterGroup(FormatterGroup):
def __init__(self):
super().__init__(
base=PDFFormatter(),
icon=IconFormatter(name="FileEarmarkPdf"),
tag=IconFormatter(name="FileEarmarkPdf"),
small=IconFormatter(name="FileEarmarkPdf"),
thumbnail=PDFFormatter(),
full=PDFFormatter(classes="max-w-full max-h-full"),
gallery=PDFFormatter(classes="h-full"),
)
| meerkat-main | meerkat/interactive/formatter/pdf.py |
import numpy as np
import pandas as pd
from ..app.src.lib.component.core.checkbox import Checkbox
from .base import Formatter, FormatterGroup
from .icon import IconFormatter
class BooleanFormatter(Formatter):
component_class: type = Checkbox
data_prop: str = "checked"
def encode(self, cell: bool) -> bool:
if isinstance(cell, np.generic):
if pd.isna(cell):
return "NaN"
return cell.item()
if hasattr(cell, "as_py"):
return cell.as_py()
return str(cell)
class BooleanFormatterGroup(FormatterGroup):
def __init__(self):
super().__init__(
base=BooleanFormatter(),
icon=IconFormatter(name="CheckSquare"),
)
| meerkat-main | meerkat/interactive/formatter/boolean.py |
from typing import Any
from meerkat.interactive.app.src.lib.component.core.tensor import Tensor
from .base import Formatter, FormatterGroup
from .icon import IconFormatter
class TensorFormatter(Formatter):
"""Formatter for an embedding."""
component_class: type = Tensor
def encode(self, cell: Any):
return {
"data": cell.tolist(),
"shape": list(cell.shape),
"dtype": str(cell.dtype),
}
class TensorFormatterGroup(FormatterGroup):
def __init__(self, dtype: str = None):
super().__init__(
base=TensorFormatter(dtype=dtype),
icon=IconFormatter(name="BoxFill"),
)
| meerkat-main | meerkat/interactive/formatter/tensor.py |
import textwrap
from typing import Any, Dict
import numpy as np
from pandas.io.formats.format import format_array
from meerkat.interactive.app.src.lib.component.core.text import Text
from meerkat.interactive.formatter.base import BaseFormatter, FormatterGroup
from meerkat.interactive.formatter.icon import IconFormatter
class TextFormatter(BaseFormatter):
"""Formatter for Text component.
Args:
component_class: The component class to format.
data_prop: The property name of the data to format.
variants: The variants of the component.
"""
component_class: type = Text
data_prop: str = "data"
def __init__(self, classes: str = ""):
self.classes = classes
def encode(self, cell: Any):
return str(cell)
@property
def props(self) -> Dict[str, Any]:
return {"classes": self.classes}
def _get_state(self) -> Dict[str, Any]:
return {
"classes": self.classes,
}
def _set_state(self, state: Dict[str, Any]):
self.classes = state["classes"]
def html(self, cell: Any):
cell = self.encode(cell)
if isinstance(cell, str):
cell = textwrap.shorten(cell, width=100, placeholder="...")
return format_array(np.array([cell]), formatter=None)[0]
class TextFormatterGroup(FormatterGroup):
def __init__(self, classes: str = ""):
super().__init__(
icon=IconFormatter(name="FileEarmarkFont"),
base=TextFormatter(classes=classes),
tiny=TextFormatter(classes=classes),
small=TextFormatter(classes=classes),
thumbnail=TextFormatter(classes=classes),
table=TextFormatter(
classes="max-h-64 overflow-hidden focus:overflow-y-scroll " + classes
),
gallery=TextFormatter(classes="aspect-video h-full p-2 " + classes),
tag=TextFormatter(
classes="whitespace-nowrap text-ellipsis overflow-hidden text-right "
+ classes
), # noqa: E501
)
| meerkat-main | meerkat/interactive/formatter/text.py |
import base64
import os
from io import BytesIO
from typing import Any, Dict, Union
from scipy.io.wavfile import write
from meerkat.cells.audio import Audio as AudioCell
from meerkat.columns.deferred.base import DeferredCell
from meerkat.interactive.formatter.icon import IconFormatter
from ..app.src.lib.component.core.audio import Audio
from .base import BaseFormatter, FormatterGroup
class AudioFormatter(BaseFormatter):
component_class = Audio
data_prop: str = "data"
def __init__(self, downsampling_factor: int = 1, classes: str = ""):
"""
Args:
sampling_rate_factor: The factor by which to multiply the sampling rate.
classes: The CSS classes to apply to the audio.
"""
self.downsampling_factor = downsampling_factor
self.classes = classes
def encode(self, cell: Union[AudioCell, bytes]) -> str:
"""Encodes audio as a base64 string.
Args:
cell: The image to encode.
skip_copy: If True, the image may be modified in place.
Set to ``True`` if the image is already a copy
or is loaded dynamically (e.g. DeferredColumn).
This may save time for large images.
"""
if isinstance(cell, DeferredCell):
cell = cell()
# If the audio is already encoded, return it.
if isinstance(cell, bytes):
return "data:audio/mpeg;base64,{im_base_64}".format(
im_base_64=base64.b64encode(cell).decode()
)
arr = cell.data
sampling_rate = cell.sampling_rate
import torch
if isinstance(arr, torch.Tensor):
arr = arr.cpu().numpy()
arr = arr[:: self.downsampling_factor]
sampling_rate = sampling_rate // self.downsampling_factor
with BytesIO() as buffer:
write(buffer, sampling_rate, arr)
return "data:audio/mpeg;base64,{im_base_64}".format(
im_base_64=base64.b64encode(buffer.getvalue()).decode()
)
@property
def props(self) -> Dict[str, Any]:
return {"classes": self.classes}
def html(self, cell: AudioCell) -> str:
encoded = self.encode(cell)
return (
"<audio controls={true} autoplay={false}>"
+ f"<source src={encoded} /></audio>"
)
def _get_state(self) -> Dict[str, Any]:
return {"classes": self.classes}
def _set_state(self, state: Dict[str, Any]):
self.classes = state["classes"]
class AudioFormatterGroup(FormatterGroup):
formatter_class: type = AudioFormatter
def __init__(self, classes: str = ""):
super().__init__(
icon=IconFormatter(name="Soundwave"),
base=self.formatter_class(),
)
class DeferredAudioFormatter(AudioFormatter):
component_class: type = Audio
data_prop: str = "data"
def encode(self, audio: DeferredCell) -> str:
if hasattr(audio, "absolute_path"):
absolute_path = audio.absolute_path
if isinstance(absolute_path, os.PathLike):
absolute_path = str(absolute_path)
if isinstance(absolute_path, str) and absolute_path.startswith("http"):
return audio.absolute_path
audio = audio()
return super().encode(audio)
class DeferredAudioFormatterGroup(AudioFormatterGroup):
formatter_class: type = DeferredAudioFormatter
| meerkat-main | meerkat/interactive/formatter/audio.py |
import base64
import os
from io import BytesIO
from typing import Any, Dict, Optional, Tuple, Union
import numpy as np
from PIL import Image as PILImage
from meerkat import env
from meerkat.columns.deferred.base import DeferredCell
from meerkat.interactive.formatter.icon import IconFormatter
from meerkat.tools.lazy_loader import LazyLoader
from ..app.src.lib.component.core.image import Image
from .base import BaseFormatter, FormatterGroup
torch = LazyLoader("torch")
class ImageFormatter(BaseFormatter):
component_class = Image
data_prop: str = "data"
def __init__(
self,
max_size: Tuple[int] = None,
classes: str = "",
mode: Optional[str] = None,
enable_zoom: Union[bool, float] = False,
enable_pan: bool = False,
):
super().__init__()
self.max_size = max_size
self.classes = classes
self.mode = mode
self.enable_zoom = enable_zoom
self.enable_pan = enable_pan
def encode(self, cell: PILImage, skip_copy: bool = False, mode: str = None) -> str:
"""Encodes an image as a base64 string.
Args:
cell: The image to encode.
skip_copy: If True, the image may be modified in place.
Set to ``True`` if the image is already a copy
or is loaded dynamically (e.g. DeferredColumn).
This may save time for large images.
"""
if mode is None:
mode = self.mode
if env.package_available("torch") and isinstance(cell, torch.Tensor):
cell = cell.cpu().numpy()
if isinstance(cell, np.ndarray):
cell = PILImage.fromarray(cell, mode=mode)
# We can skip copying if we are constructing the image from a numpy array.
skip_copy = True
ftype = "png" if mode == "RGBA" else "jpeg"
with BytesIO() as buffer:
if self.max_size:
# Image.thumbnail modifies the image in place, so we need to
# make a copy first.
if not skip_copy:
cell = cell.copy()
cell.thumbnail(self.max_size)
cell.save(buffer, ftype)
return "data:image/{ftype};base64,{im_base_64}".format(
ftype=ftype, im_base_64=base64.b64encode(buffer.getvalue()).decode()
)
@property
def props(self) -> Dict[str, Any]:
return {
"classes": self.classes,
"enable_zoom": self.enable_zoom,
"enable_pan": self.enable_pan,
}
def html(self, cell: Image) -> str:
encoded = self.encode(cell)
return f'<img src="{encoded}">'
def _get_state(self) -> Dict[str, Any]:
return {
"max_size": self.max_size,
"classes": self.classes,
"mode": self.mode,
"enable_zoom": self.enable_zoom,
"enable_pan": self.enable_pan,
}
def _set_state(self, state: Dict[str, Any]):
self.max_size = state["max_size"]
self.classes = state["classes"]
self.mode = state["mode"]
if "enable_zoom" in state:
self.enable_zoom = state["enable_zoom"]
if "enable_pan" in state:
self.enable_pan = state["enable_pan"]
class ImageFormatterGroup(FormatterGroup):
formatter_class: type = ImageFormatter
def __init__(self, classes: str = "", mode: Optional[str] = None):
super().__init__(
icon=IconFormatter(name="Image"),
base=self.formatter_class(
classes=classes, mode=mode, enable_zoom=True, enable_pan=True
),
tiny=self.formatter_class(max_size=[32, 32], classes=classes, mode=mode),
small=self.formatter_class(max_size=[64, 64], classes=classes, mode=mode),
thumbnail=self.formatter_class(
max_size=[256, 256], classes=classes, mode=mode
),
gallery=self.formatter_class(
max_size=[512, 512], classes="h-full w-full" + " " + classes, mode=mode
),
)
# TODO: Add support for displaying numpy arrays and torch tensors as images.
# This breaks currently with html rendering.
class DeferredImageFormatter(ImageFormatter):
component_class: type = Image
data_prop: str = "data"
def encode(self, image: DeferredCell) -> str:
if hasattr(image, "absolute_path"):
absolute_path = image.absolute_path
if isinstance(absolute_path, os.PathLike):
absolute_path = str(absolute_path)
if isinstance(absolute_path, str) and absolute_path.startswith("http"):
return image.absolute_path
image = image()
return super().encode(image, skip_copy=True)
class DeferredImageFormatterGroup(ImageFormatterGroup):
formatter_class: type = DeferredImageFormatter
| meerkat-main | meerkat/interactive/formatter/image.py |
from __future__ import annotations
import collections
from abc import ABC, abstractmethod, abstractproperty
from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Type, Union
import yaml
from meerkat.columns.deferred.base import DeferredCell
from meerkat.tools.utils import MeerkatDumper, MeerkatLoader
if TYPE_CHECKING:
from meerkat.interactive.app.src.lib.component.abstract import BaseComponent
class Variant:
def __init__(*args, **kwargs):
pass
class FormatterGroup(collections.abc.Mapping):
"""A formatter group is a mapping from formatter placeholders to
formatters.
Data in a Meerkat column sometimes need to be displayed differently in different
GUI contexts. For example, in a table, we display thumbnails of images, but in a
carousel view, we display the full image.
Because most components in Meerkat work on any data type, it is important that
they are implemented in a formatter-agnostic way. So, instead of specifying
formatters, components make requests for data specifying a *formatter placeholder*.
For example, the {class}`mk.gui.Gallery` component requests data using the
`thumbnail` formatter placeholder.
For a specific column of data, we specify which formatters to use for each
placeholder using a *formatter group*. A formatter group is a mapping from
formatter placeholders to formatters. Each column in Meerkat has a
`formatter_group` property. A column's formatter group controls how it will be
displayed in different contexts in Meerkat GUIs.
Args:
base (FormatterGroup): The base formatter group to use.
**kwargs: The formatters to add to the formatter group.
"""
def __init__(self, base: BaseFormatter = None, **kwargs):
if base is None:
from meerkat.interactive.formatter import TextFormatter
# everything has a str method so this is a safe default
base = TextFormatter()
if not isinstance(base, BaseFormatter):
raise TypeError("base must be a Formatter")
for key, value in kwargs.items():
if key not in formatter_placeholders:
raise ValueError(
f"The key {key} is not a registered formatter "
"placeholder. Use `mk.register_formatter_placeholder`"
)
if not isinstance(value, BaseFormatter):
raise TypeError(
f"FormatterGroup values must be Formatters, not {type(value)}"
)
# must provide a base formatter
self._dict = dict(base=base, **kwargs)
def __getitem__(self, key: Union[FormatterPlaceholder, str]) -> BaseFormatter:
"""Get the formatter for the given formatter placeholder.
Args:
key (FormatterPlaceholder): The formatter placeholder.
Returns:
(Formatter) The formatter for the formatter placeholder.
"""
if isinstance(key, str):
if key in formatter_placeholders:
key = formatter_placeholders[key]
else:
key = FormatterPlaceholder(key, [])
if key.name in self._dict:
return self._dict.__getitem__(key.name)
for fallback in key.fallbacks:
if fallback.name in self._dict:
return self.__getitem__(fallback)
return self._dict["base"]
def __setitem__(
self, key: Union[FormatterPlaceholder, str], value: BaseFormatter
) -> None:
if key not in formatter_placeholders:
raise ValueError(
f"The key {key} is not a registered formatter "
"placeholder. Use `mk.register_formatter_placeholder`"
)
if not isinstance(value, BaseFormatter):
raise TypeError(
f"FormatterGroup values must be Formatters, not {type(value)}"
)
return self._dict.__setitem__(key, value)
def defer(self):
return deferred_formatter_group(self)
def __len__(self) -> int:
return len(self._dict)
def __iter__(self) -> Iterator:
return iter(self._dict)
def update(self, other: Union[FormatterGroup, Dict]):
self._dict.update(other)
def copy(self):
new = self.__class__.__new__(self.__class__)
new._dict = self._dict.copy()
return new
@staticmethod
def to_yaml(dumper: yaml.Dumper, data: BaseFormatter):
"""This function is called by the YAML dumper to convert a
:class:`Formatter` object into a YAML node.
It should not be called directly.
"""
data = {
"class": type(data),
"dict": data._dict,
}
return dumper.represent_mapping("!FormatterGroup", data)
@staticmethod
def from_yaml(loader, node):
"""This function is called by the YAML loader to convert a YAML node
into an :class:`Formatter` object.
It should not be called directly.
"""
data = loader.construct_mapping(node)
formatter = data["class"].__new__(data["class"])
formatter._dict = data["dict"]
return formatter
MeerkatDumper.add_multi_representer(FormatterGroup, FormatterGroup.to_yaml)
MeerkatLoader.add_constructor("!FormatterGroup", FormatterGroup.from_yaml)
def deferred_formatter_group(group: FormatterGroup) -> FormatterGroup:
"""Wrap all formatters in a FormatterGroup with a DeferredFormatter.
Args:
group (FormatterGroup): The FormatterGroup to wrap.
Returns:
(FormatterGroup) A new FormatterGroup with all formatters wrapped in a
DeferredFormatter.
"""
new_group = group.copy()
for name, formatter in group.items():
new_group[name] = DeferredFormatter(formatter)
return new_group
class FormatterPlaceholder:
def __init__(
self,
name: str,
fallbacks: List[Union[str, FormatterPlaceholder]],
description: str = "",
):
global formatter_placeholders
self.name = name
self.fallbacks = [
fb if isinstance(fb, FormatterPlaceholder) else formatter_placeholders[fb]
for fb in fallbacks
]
if name != "base":
self.fallbacks.append(FormatterPlaceholder("base", fallbacks=[]))
self.description = description
formatter_placeholders = {
"base": FormatterPlaceholder("base", []),
}
def register_placeholder(
name: str, fallbacks: List[FormatterPlaceholder] = [], description: str = ""
):
"""Register a new formatter placeholder.
Args:
name (str): The name of the formatter placeholder.
fallbacks (List[FormatterPlaceholder]): The fallbacks for the formatter
placeholder.
description (str): A description of the formatter placeholder.
"""
if name in formatter_placeholders:
raise ValueError(f"{name} is already a registered formatter placeholder")
formatter_placeholders[name] = FormatterPlaceholder(
name=name, fallbacks=fallbacks, description=description
)
# register core formatter placeholders
register_placeholder("small", fallbacks=[], description="A small version of the data.")
register_placeholder(
"tiny", fallbacks=["small"], description="A tiny version of the data."
)
register_placeholder(
"thumbnail", fallbacks=["small"], description="A thumbnail of the data."
)
register_placeholder(
"icon", fallbacks=["tiny"], description="An icon representing the data."
)
register_placeholder(
"tag",
fallbacks=["tiny"],
description="A small version of the data meant to go in a tag field.",
)
register_placeholder(
"full",
fallbacks=["base"],
description="A full version of the data.",
)
class BaseFormatter(ABC):
component_class: Type["BaseComponent"]
data_prop: str = "data"
static_encode: bool = False
def encode(self, cell: Any, **kwargs):
"""Encode the cell on the backend before sending it to the frontend.
The cell is lazily loaded, so when used on a LambdaColumn,
``cell`` will be a ``LambdaCell``. This is important for
displays that don't actually need to apply the lambda in order
to display the value.
"""
return cell
@abstractproperty
def props(self):
return self._props
@abstractmethod
def _get_state(self) -> Dict[str, Any]:
pass
@abstractmethod
def _set_state(self, state: Dict[str, Any]):
pass
@staticmethod
def to_yaml(dumper: yaml.Dumper, data: BaseFormatter):
"""This function is called by the YAML dumper to convert a
:class:`Formatter` object into a YAML node.
It should not be called directly.
"""
data = {
"class": type(data),
"state": data._get_state(),
}
return dumper.represent_mapping("!Formatter", data)
@staticmethod
def from_yaml(loader, node):
"""This function is called by the YAML loader to convert a YAML node
into an :class:`Formatter` object.
It should not be called directly.
"""
data = loader.construct_mapping(node, deep=True)
formatter = data["class"].__new__(data["class"])
formatter._set_state(data["state"])
return formatter
def html(self, cell: Any):
"""When not in interactive mode, objects are visualized using static
html.
This method should produce that static html for the cell.
"""
return str(cell)
class Formatter(BaseFormatter):
# TODO: set the signature of the __init__ so it works with autocomplete and docs
def __init__(self, **kwargs):
for k in kwargs:
if k not in self.component_class.prop_names:
raise ValueError(f"{k} is not a valid prop for {self.component_class}")
for prop_name, field in self.component_class.__fields__.items():
if field.name != self.data_prop and prop_name not in kwargs:
if field.required:
raise ValueError("""Missing required argument.""")
kwargs[prop_name] = field.default
self._props = kwargs
def encode(self, cell: str):
return cell
@property
def props(self) -> Dict[str, Any]:
return self._props
def _get_state(self) -> Dict[str, Any]:
return {
"_props": self._props,
}
def _set_state(self, state: Dict[str, Any]):
self._props = state["_props"]
MeerkatDumper.add_multi_representer(BaseFormatter, BaseFormatter.to_yaml)
MeerkatLoader.add_constructor("!Formatter", BaseFormatter.from_yaml)
class DeferredFormatter(BaseFormatter):
def __init__(self, formatter: BaseFormatter):
self.wrapped = formatter
def encode(self, cell: DeferredCell, **kwargs):
if self.wrapped.static_encode:
return self.wrapped.encode(None, **kwargs)
return self.wrapped.encode(cell(), **kwargs)
@property
def component_class(self):
return self.wrapped.component_class
@property
def data_prop(self):
return self.wrapped.data_prop
@property
def props(self):
return self.wrapped.props
def html(self, cell: DeferredCell):
return self.wrapped.html(cell())
def _get_state(self):
data = {
"wrapped": {
"class": self.wrapped.__class__,
"state": self.wrapped._get_state(),
},
}
return data
def _set_state(self, state: Dict[str, Any]):
wrapped_state = state["wrapped"]
wrapped = wrapped_state["class"].__new__(wrapped_state["class"])
wrapped._set_state(wrapped_state["state"])
self.wrapped = wrapped
MeerkatDumper.add_multi_representer(DeferredFormatter, DeferredFormatter.to_yaml)
MeerkatLoader.add_constructor("!DeferredFormatter", DeferredFormatter.from_yaml)
| meerkat-main | meerkat/interactive/formatter/base.py |
from .main import app as MeerkatAPI # noqa: F401
from .routers import ( # noqa: F401
dataframe,
endpoint,
llm,
page,
sliceby,
store,
subscribe,
)
| meerkat-main | meerkat/interactive/api/__init__.py |
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI(debug=True)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
| meerkat-main | meerkat/interactive/api/main.py |
import logging
import traceback
from fastapi import HTTPException
from fastapi.encoders import jsonable_encoder
from meerkat.interactive.endpoint import Endpoint, endpoint
from meerkat.interactive.graph import Store, trigger
from meerkat.interactive.modification import StoreModification
from meerkat.interactive.utils import get_custom_json_encoder, is_equal
from meerkat.state import state
from meerkat.tools.lazy_loader import LazyLoader
torch = LazyLoader("torch")
logger = logging.getLogger(__name__)
# KG: do not use -> List[Modification] as the return type for the `update`
# fn. This causes Pydantic to drop several fields from the
# StoreModification object (it only ends up sending the ids).
@endpoint(prefix="/store", route="/{store}/update/")
def update(store: Store, value=Endpoint.EmbeddedBody()):
"""Triggers the computational graph when a store on the frontend
changes."""
logger.debug(f"Updating store {store} with value {value}.")
# TODO: the interface sends store_triggers for all stores when it starts
# up -- these requests should not be being sent.
# These requests are indirectly ignored here because we check if the
# value of the store actually changed (and these initial post requests
# do not change the value of the store).
# Check if this request would actually change the value of the store
# current_store_value = store_modification.node
# TODO: Verify this works for nested stores.
if is_equal(store.value, value):
logger.debug("Store value did not change. Skipping trigger.")
return []
# Ready the modification queue
state.modification_queue.ready()
# Set the new value of the store
store.set(value)
# Trigger on the store modification: leads to modifications on the graph
try:
modifications = trigger()
except Exception as e:
logger.error(traceback.format_exc())
raise HTTPException(status_code=400, detail=str(e)) from e
# Only return modifications that are not backend_only
modifications = [
m
for m in modifications
if not (isinstance(m, StoreModification) and m.backend_only)
]
logger.debug(f"Returning modifications: {modifications}.")
# Return the modifications
return jsonable_encoder(
modifications,
custom_encoder=get_custom_json_encoder(),
)
| meerkat-main | meerkat/interactive/api/routers/store.py |
import asyncio
import json
import logging
from sse_starlette.sse import EventSourceResponse
from meerkat.interactive.endpoint import endpoint
logger = logging.getLogger(__name__)
STREAM_DELAY = 0.150 # second
RETRY_TIMEOUT = 15000 # milisecond
async def progress_generator():
from meerkat.state import state
progress_queue = state.progress_queue
while True:
# Checks for any progress and return to client if any
progress = progress_queue.clear()
if progress:
for item in progress:
if isinstance(item, list):
# Start events just send the total length
# of the progressbar
logger.debug(f"Sending start event with {item}.")
yield {
"event": "start",
"id": "message_id",
"retry": RETRY_TIMEOUT,
"data": json.dumps(item),
}
elif item is None:
logger.debug("Sending end event.")
yield {
"event": "end",
"id": "message_id",
"retry": RETRY_TIMEOUT,
"data": "",
}
elif isinstance(item, str):
logger.debug(f"Sending endpoint event with {item}.")
yield {
"event": "endpoint",
"id": "message_id",
"retry": RETRY_TIMEOUT,
"data": json.dumps(item),
}
else:
# Progress events send the current progress
# and the operation name
logger.debug(f"Sending progress event with {item}.")
yield {
"event": "progress",
"id": "message_id",
"retry": RETRY_TIMEOUT,
"data": json.dumps(item),
}
await asyncio.sleep(STREAM_DELAY)
@endpoint(prefix="/subscribe", route="/progress/", method="GET")
def progress():
return EventSourceResponse(progress_generator())
| meerkat-main | meerkat/interactive/api/routers/subscribe.py |
from typing import Dict, List
from fastapi import HTTPException
from pydantic import BaseModel
from meerkat.interactive.endpoint import Endpoint, endpoint
from meerkat.interactive.formatter import BasicFormatter
from meerkat.ops.sliceby.sliceby import SliceBy, SliceKey
from meerkat.state import state
from .dataframe import RowsResponse, _get_column_infos
class InfoResponse(BaseModel):
id: str
type: str
n_slices: int
slice_keys: List[SliceKey]
class Config:
# need a smart union here to avoid casting ints to strings in SliceKey
# https://pydantic-docs.helpmanual.io/usage/types/#unions
smart_union = True
@endpoint(prefix="/sliceby", route="/{sb}/info/", method="GET")
def get_info(sb: SliceBy) -> InfoResponse:
# FIXME Make sure the SliceBy object works for this endpoint
return InfoResponse(
id=sb.id,
type=type(sb).__name__,
n_slices=len(sb),
slice_keys=sb.slice_keys,
)
class SliceByRowsRequest(BaseModel):
# TODO (sabri): add support for data validation
slice_key: SliceKey
start: int = None
end: int = None
indices: List[int] = None
columns: List[str] = None
class Config:
smart_union = True
@endpoint(prefix="/sliceby", route="/{sb}/rows/")
def get_rows(
sb: SliceBy,
request: SliceByRowsRequest,
) -> RowsResponse:
"""Get rows from a DataFrame as a JSON object."""
# FIXME Make sure the SliceBy object works for this endpoint
slice_key = request.slice_key
full_length = sb.get_slice_length(slice_key)
column_infos = _get_column_infos(sb.data, request.columns)
sb = sb[[info.name for info in column_infos]]
if request.indices is not None:
df = sb.slice[slice_key, request.indices]
indices = request.indices
elif request.start is not None:
df = sb.slice[slice_key, request.start : request.end]
indices = list(range(request.start, request.end))
else:
raise ValueError()
rows = []
for row in df:
rows.append(
[df[info.name].formatter.encode(row[info.name]) for info in column_infos]
)
return RowsResponse(
columnInfos=column_infos,
rows=rows,
fullLength=full_length,
indices=indices,
)
@endpoint(prefix="/sliceby", route="/{sb}/aggregate/")
def aggregate(
sb: SliceBy,
aggregation_id: str = Endpoint.EmbeddedBody(None),
aggregation: str = Endpoint.EmbeddedBody(None),
accepts_df: bool = Endpoint.EmbeddedBody(False),
columns: List[str] = Endpoint.EmbeddedBody(None),
) -> Dict:
# FIXME Make sure the SliceBy object works for this endpoint
if columns is not None:
sb = sb[columns]
if (aggregation_id is None) == (aggregation is None):
raise HTTPException(
status_code=400,
detail="Must specify either aggregation_id or aggregation",
)
if aggregation_id is not None:
aggregation = state.identifiables.get(id=aggregation_id, group="aggregations")
value = sb.aggregate(aggregation, accepts_df=accepts_df)
else:
if aggregation not in ["mean", "sum", "min", "max"]:
raise HTTPException(
status_code=400, detail=f"Invalid aggregation {aggregation}"
)
value = sb.aggregate(aggregation)
# convert to dict format for output
df = value.to_pandas().set_index(sb.by)
dct = df.applymap(BasicFormatter().encode).to_dict()
return dct
| meerkat-main | meerkat/interactive/api/routers/sliceby.py |
from typing import Any, Dict, List, Optional, Union
from fastapi import HTTPException
from pydantic import BaseModel, StrictInt, StrictStr
from meerkat.dataframe import DataFrame
from meerkat.interactive.endpoint import Endpoint, endpoint
class ColumnInfo(BaseModel):
name: str
type: str
cellComponent: str
cellProps: Dict[str, Any]
cellDataProp: str
class SchemaResponse(BaseModel):
id: str
columns: List[ColumnInfo]
nrows: int = None
primaryKey: str = None
@endpoint(prefix="/df", route="/{df}/schema/")
def schema(
df: DataFrame,
columns: List[str] = Endpoint.EmbeddedBody(None),
formatter: Union[str, Dict[str, str]] = Endpoint.EmbeddedBody("base"),
) -> SchemaResponse:
columns = df.columns if columns is None else columns
if isinstance(formatter, str):
formatter = {column: formatter for column in columns}
return SchemaResponse(
id=df.id,
columns=_get_column_infos(df, columns, formatter_placeholders=formatter),
nrows=len(df),
primaryKey=df.primary_key_name,
)
def _get_column_infos(
df: DataFrame,
columns: List[str] = None,
formatter_placeholders: Dict[str, str] = None,
):
if columns is None:
columns = df.columns
else:
missing_columns = set(columns) - set(df.columns)
if len(missing_columns) > 0:
raise HTTPException(
status_code=404,
detail=(
f"Requested columns {columns} do not exist in dataframe"
f" with id {df.id}"
),
)
columns = [column for column in columns if not column.startswith("_")]
if df.primary_key_name is not None and df.primary_key_name not in columns:
columns += [df.primary_key_name]
# TODO: Check if this is the right fix.
if formatter_placeholders is None:
formatter_placeholders = {}
elif isinstance(formatter_placeholders, str):
formatter_placeholders = {
column: formatter_placeholders for column in df.columns
}
out = [
ColumnInfo(
name=col,
type=type(df[col]).__name__,
cellComponent=df[col]
.formatters[formatter_placeholders.get(col, "base")]
.component_class.alias,
cellProps=df[col].formatters[formatter_placeholders.get(col, "base")].props,
cellDataProp=df[col]
.formatters[formatter_placeholders.get(col, "base")]
.data_prop,
)
for col in columns
]
return out
class RowsResponse(BaseModel):
columnInfos: List[ColumnInfo]
posidxs: List[int] = None
rows: List[List[Any]]
fullLength: int
primaryKey: Optional[str] = None
@endpoint(prefix="/df", route="/{df}/rows/")
def rows(
df: DataFrame,
start: int = Endpoint.EmbeddedBody(None),
end: int = Endpoint.EmbeddedBody(None),
posidxs: List[int] = Endpoint.EmbeddedBody(None),
key_column: str = Endpoint.EmbeddedBody(None),
keyidxs: List[Union[StrictInt, StrictStr]] = Endpoint.EmbeddedBody(None),
columns: List[str] = Endpoint.EmbeddedBody(None),
formatter: Union[str, Dict[str, str]] = Endpoint.EmbeddedBody("base"),
shuffle: bool = Endpoint.EmbeddedBody(False),
) -> RowsResponse:
"""Get rows from a DataFrame as a JSON object."""
if columns is None:
columns = df.columns
if isinstance(formatter, str):
formatter = {column: formatter for column in columns}
full_length = len(df)
column_infos = _get_column_infos(df, columns, formatter_placeholders=formatter)
if shuffle:
df = df.shuffle()
df = df[[info.name for info in column_infos]]
if posidxs is not None:
df = df[posidxs]
posidxs = posidxs
elif start is not None:
if end is None:
end = len(df)
else:
end = min(end, len(df))
df = df[start:end]
posidxs = list(range(start, end))
elif keyidxs is not None:
if key_column is None:
if df.primary_key is None:
raise ValueError(
"Must provide key_column if keyidxs are provided and no "
"primary_key on dataframe."
)
df = df.loc[keyidxs]
else:
# FIXME(sabri): this will only work if key_column is a pandas column
df = df[df[key_column].isin(keyidxs)]
else:
raise ValueError()
rows = []
for row in df:
rows.append(
[
df[info.name]
.formatters[formatter.get(info.name, "base")]
.encode(row[info.name])
for info in column_infos
]
)
return RowsResponse(
columnInfos=column_infos,
rows=rows,
fullLength=full_length,
posidxs=posidxs,
primaryKey=df.primary_key_name,
)
| meerkat-main | meerkat/interactive/api/routers/dataframe.py |
meerkat-main | meerkat/interactive/api/routers/__init__.py |
|
from fastapi.encoders import jsonable_encoder
from meerkat.interactive import Page
from meerkat.interactive.endpoint import endpoint
from meerkat.interactive.utils import get_custom_json_encoder
from meerkat.tools.lazy_loader import LazyLoader
torch = LazyLoader("torch")
@endpoint(prefix="/page", route="/{page}/config/", method="GET")
def config(page: Page):
return jsonable_encoder(
# TODO: we should not be doing anything except page.frontend
# here. This is a temp workaround to avoid getting an
# exception in the notebook.
page.frontend if isinstance(page, Page) else page,
custom_encoder=get_custom_json_encoder(),
)
| meerkat-main | meerkat/interactive/api/routers/page.py |
# TODO(karan): fix and generalize these APIs
import functools
import random
from typing import List
from fastapi import APIRouter, Body, HTTPException
from pydantic import BaseModel
from meerkat.state import state
router = APIRouter(
prefix="/llm",
tags=["llm"],
responses={404: {"description": "Not found"}},
)
EmbeddedBody = functools.partial(Body, embed=True)
class CategoryGenerationResponse(BaseModel):
categories: List[str]
class CategorizationGenerationResponse(BaseModel):
categories: List[str]
@router.post("/generate/categories")
def generate_categories(
dataset_description: str = EmbeddedBody(),
hint: str = EmbeddedBody(),
n_categories: int = EmbeddedBody(default=20),
) -> CategoryGenerationResponse:
"""Generate a list of categories for a dataset using an LLM."""
from manifest import Prompt
state.llm.set(client="ai21", engine="j1-jumbo")
try:
response = state.llm.get().run(
Prompt(
f"""
List {n_categories} distinct attributes that can be used to tag a dataset.
---
Dataset: {dataset_description}
Hint: {hint}
Attributes:
"""
),
top_k_return=1,
temperature=0.5,
max_tokens=128,
stop_token="\n---",
)
print(response)
lines = response.split("\n")
categories = [line.split(". ")[-1] for line in lines]
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
return CategoryGenerationResponse(
categories=categories,
)
@router.post("/generate/categorization")
def generate_categorization(
description: str = EmbeddedBody(),
existing_categories: List[str] = EmbeddedBody(default=["none"]),
) -> CategorizationGenerationResponse:
"""Generate a list of categories for a dataset using an LLM."""
from manifest import Prompt
state.llm.set(client="ai21", engine="j1-jumbo")
random.shuffle(existing_categories)
try:
response = state.llm.get().run(
Prompt(
f"""
List 5 distinct possibilities that could be used to categorize an attribute. The attribute description is provided.
---
Attribute description: types of eyewear
Existing categories: none
Additional categories:
1. sunglasses
2. eyeglasses
3. goggles
4. blindfolds
5. vr headsets
---
Attribute description: age groups (words not ranges)
Existing categories: infants, teenagers
Additional categories:
1. toddlers
2. children
3. teens
4. adults
5. seniors
---
Attribute description: styles of art
Existing categories: abstract, modern, impressionism
Additional categories:
1. realism
2. surrealism
3. cubism
4. psychedelic
5. contemporary
---
Attribute description: political leanings
Existing categories: none
Additional categories:
1. authoritarian
2. libertarian
3. liberal
4. conservative
5. anarchist
---
Attribute description: {description}
Existing categories: {", ".join(existing_categories)}
More categories:
""" # noqa: E501
),
top_k_return=1,
temperature=0.5,
max_tokens=128,
stop_token="\n---",
)
print(response)
lines = response.split("\n")
categories = [line.split(". ")[-1] for line in lines]
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
return CategorizationGenerationResponse(
categories=categories,
)
| meerkat-main | meerkat/interactive/api/routers/llm.py |
import logging
import traceback
from fastapi import HTTPException
from fastapi.encoders import jsonable_encoder
from meerkat.interactive.endpoint import Endpoint, endpoint
from meerkat.interactive.utils import get_custom_json_encoder
from meerkat.tools.lazy_loader import LazyLoader
torch = LazyLoader("torch")
logger = logging.getLogger(__name__)
@endpoint(prefix="/endpoint", route="/{endpoint}/dispatch/")
def dispatch(
endpoint: Endpoint,
payload: dict,
) -> dict:
"""Call an endpoint."""
logger.debug(f"Dispatching endpoint {endpoint} with payload {payload}.")
from meerkat.interactive.modification import StoreModification
# `payload` is a dict with {detail: {key: value} | primitive}
# Unpack the payload to build the fn_kwargs
fn_kwargs = {}
kwargs = payload["detail"]
if isinstance(kwargs, dict):
fn_kwargs = kwargs
try:
# Run the endpoint
result, modifications = endpoint.partial(**fn_kwargs).run()
except Exception as e:
# General exception should be converted to a HTTPException
# that fastapi can handle.
from meerkat.state import state
logger.debug("Exception in dispatch", exc_info=True)
state.progress_queue.add(None)
logger.error(traceback.format_exc())
raise HTTPException(status_code=400, detail=str(e)) from e
# Only return store modifications that are not backend_only
modifications = [
m
for m in modifications
if not (isinstance(m, StoreModification) and m.backend_only)
]
# Return the modifications and the result to the frontend
# Need to support sending back numpy arrays, torch tensors, and pandas series
return jsonable_encoder(
{"result": result, "modifications": modifications, "error": None},
custom_encoder=get_custom_json_encoder(),
)
| meerkat-main | meerkat/interactive/api/routers/endpoint.py |
from setuptools import find_packages, setup
setup(
name="app",
version="0.0.1",
packages=find_packages(),
include_package_data=True,
install_requires=[
"meerkat-ml",
],
)
| meerkat-main | meerkat/interactive/templates/setup.py |
from app.src.lib.components import ExampleComponent
import meerkat as mk
# Import and use the ExampleComponent
example_component = ExampleComponent(name="Meerkat")
# Launch the Meerkat GUI
# mk.gui.start() # not required for running with `mk run`
page = mk.gui.Page(component=example_component, id="example")
page.launch()
| meerkat-main | meerkat/interactive/templates/example.py |
from meerkat import classproperty
from meerkat.interactive import Component
class LibraryMixin:
@classproperty
def namespace(cls):
return "custom"
# Component should always be the last base class
class ExampleComponent(LibraryMixin, Component):
"""Make custom components by extending the `Component` class.
Add the `namespace` and `library` class properties, so that
it's easy to import and publish your components. Read our
guide on how to publish your components to learn more.
The component definition should reflect the structure of the
frontend component, and its props.
Make sure that
- all custom components are defined inside this `components` directory,
or any subdirectories.
- any `.svelte` Component file defines a corresponding Python class
in a `.py` file in the same directory.
- all components you define in any subdirectories are imported
in this `__init__.py` file of the `components` directory. Meerkat
automatically imports and registers all components defined in this
file.
For fine-grained control of which fields are synchronized
with the frontend, you can directly extend the `Component` class instead
of the `Component` class. See our documentation for details.
"""
name: str = "World"
| meerkat-main | meerkat/interactive/templates/components.init.py |
import collections.abc
from typing import List, Sequence, Union
import numpy as np
from meerkat import DataFrame, ObjectColumn
from meerkat.columns.deferred.base import DeferredColumn
from meerkat.columns.scalar import ScalarColumn
from meerkat.columns.tensor.abstract import TensorColumn
from meerkat.columns.tensor.torch import TorchTensorColumn
from meerkat.errors import MergeError
from meerkat.interactive.graph import reactive
from meerkat.ops.decorators import check_primary_key
from meerkat.provenance import capture_provenance
@capture_provenance(capture_args=["left_on", "on", "right_on", "how"])
@check_primary_key
@reactive
def merge(
left: DataFrame,
right: DataFrame,
how: str = "inner",
on: Union[str, List[str]] = None,
left_on: Union[str, List[str]] = None,
right_on: Union[str, List[str]] = None,
sort: bool = False,
suffixes: Sequence[str] = ("_x", "_y"),
validate=None,
) -> DataFrame:
"""Perform a database-style join operation between two DataFrames.
Args:
left (DataFrame): Left DataFrame.
right (DataFrame): Right DataFrame.
how (str, optional): The join type. Defaults to "inner".
on (Union[str, List[str]], optional): The columns(s) to join on.
These columns must be :class:`~meerkat.ScalarColumn`.
Defaults to None, in which case the `left_on` and `right_on` parameters
must be passed.
left_on (Union[str, List[str]], optional): The column(s) in the left DataFrame
to join on. These columns must be :class:`~meerkat.ScalarColumn`.
Defaults to None.
right_on (Union[str, List[str]], optional): The column(s) in the right DataFrame
to join on. These columns must be :class:`~meerkat.ScalarColumn`.
Defaults to None.
sort (bool, optional): Whether to sort the result DataFrame by the join key(s).
Defaults to False.
suffixes (Sequence[str], optional): Suffixes to use in the case their are
conflicting column names in the result DataFrame. Should be a sequence of
length two, with ``suffixes[0]`` the suffix for the column from the left
DataFrame and ``suffixes[1]`` the suffix for the right.
Defaults to ("_x", "_y").
validate (_type_, optional): The check to perform on the result DataFrame.
Defaults to None, in which case no check is performed. Valid options are:
* “one_to_one” or “1:1”: check if merge keys are unique in both left and
right datasets.
* “one_to_many” or “1:m”: check if merge keys are unique in left dataset.
* “many_to_one” or “m:1”: check if merge keys are unique in right dataset.
* “many_to_many” or “m:m”: allowed, but does not result in checks.
Returns:
DataFrame: The merged DataFrame.
"""
if how == "cross":
raise ValueError("DataFrame does not support cross merges.") # pragma: no cover
if (on is None) and (left_on is None) and (right_on is None):
raise MergeError("Merge expects either `on` or `left_on` and `right_on`")
left_on = on if left_on is None else left_on
right_on = on if right_on is None else right_on
# cast `left_on` and `right_on` to lists
left_on = [left_on] if isinstance(left_on, str) else left_on
right_on = [right_on] if isinstance(right_on, str) else right_on
# ensure we can merge on specified columns
_check_merge_columns(left, left_on)
_check_merge_columns(right, right_on)
# convert mk.DataFrame to pd.DataFrame so we can apply Pandas merge
# (1) only include columns we are joining on
left_df = left[left_on].to_pandas()
right_df = right[right_on].to_pandas()
# (2) add index columns, which we'll use to reconstruct the columns we excluded from
# the Pandas merge
if ("__right_indices__" in right_df) or ("__left_indices__" in left_df):
raise MergeError(
"The column names '__right_indices__' and '__left_indices__' cannot appear "
"in the right and left panels respectively. They are used by merge."
)
left_df["__left_indices__"] = np.arange(len(left_df))
right_df["__right_indices__"] = np.arange(len(right_df))
# apply pandas merge
merged_df = left_df.merge(
right_df,
how=how,
left_on=left_on,
right_on=right_on,
sort=sort,
validate=validate,
suffixes=suffixes,
)
left_indices = merged_df.pop("__left_indices__").values
right_indices = merged_df.pop("__right_indices__").values
merged_df = merged_df[list(set(left_on) & set(right_on))]
# reconstruct other columns not in the `left_on & right_on` using `left_indices`
# and `right_indices`, the row order returned by merge
def _cols_to_construct(df: DataFrame):
# don't construct columns in both `left_on` and `right_on` because we use
# `merged_df` for these
return [k for k in df.keys() if k not in (set(left_on) & set(right_on))]
left_cols_to_construct = _cols_to_construct(left)
right_cols_to_construct = _cols_to_construct(right)
new_left = (
_construct_from_indices(left[left_cols_to_construct], left_indices)
# need to check for special case where there are no columns other than those in
# the intersection of `left_on` and `right_on`
if len(left_cols_to_construct) > 0
else None
)
new_right = (
_construct_from_indices(right[right_cols_to_construct], right_indices)
# need to check for special case where there are no columns other than those in
# the intersection of `left_on` and `right_on`
if len(right_cols_to_construct) > 0
else None
)
if new_left is None and new_right is not None:
merged = new_right
elif new_left is not None and new_right is None:
merged = new_left
elif new_left is not None and new_right is not None:
# concatenate the two new dataframes if both have columns, this should be by
# far the most common case
merged = new_left.append(new_right, axis="columns", suffixes=suffixes)
else:
merged = None
if merged is not None:
# add columns in both `left_on` and `right_on`,
# casting to the column type in left
for name, column in merged_df.items():
merged.add_column(name, left[name]._clone(data=column.values))
merged.data.reorder(merged.columns[-1:] + merged.columns[:-1])
else:
merged = DataFrame.from_pandas(merged_df)
# set primary key if either the `left` or `right` has a primary key in the result
# note, the `check_primary_key` wrapper wrapper ensures that the primary_key is
# actually valid
if (left.primary_key_name is not None) and left.primary_key_name in merged:
merged.set_primary_key(left.primary_key_name, inplace=True)
elif (right.primary_key_name is not None) and right.primary_key_name in merged:
merged.set_primary_key(right.primary_key_name, inplace=True)
return merged
def _construct_from_indices(df: DataFrame, indices: np.ndarray):
if np.isnan(indices).any():
# when performing "outer", "left", and "right" merges, column indices output
# by pandas merge can include `nan` in rows corresponding to merge keys that
# only appear in one of the two panels. For these columns, we convert the
# column to ListColumn, and fill with "None" wherever indices is "nan".
data = {}
for name, col in df.items():
if isinstance(col, (TorchTensorColumn, TorchTensorColumn, ScalarColumn)):
new_col = col[indices.astype(int)]
if isinstance(new_col, TorchTensorColumn):
new_col = new_col.to(float)
elif isinstance(new_col, ScalarColumn):
if new_col.dtype != "object":
new_col = new_col.astype(float)
else:
new_col = new_col.astype(float)
new_col[np.isnan(indices)] = np.nan
data[name] = new_col
else:
data[name] = ObjectColumn(
[None if np.isnan(index) else col[int(index)] for index in indices]
)
return df._clone(data=data)
else:
# if there are no `nan`s in the indices, then we can just lazy index the
# original column
return df[indices]
def _check_merge_columns(df: DataFrame, on: List[str]):
for name in on:
column = df[name]
if isinstance(column, TensorColumn):
if len(column.shape) > 1:
raise MergeError(
f"Cannot merge on a TensorColumn column `{name}` that has more "
"than one dimension."
)
elif isinstance(column, ObjectColumn):
if not all([isinstance(cell, collections.abc.Hashable) for cell in column]):
raise MergeError(
f"Cannot merge on column `{name}`, contains unhashable objects."
)
elif isinstance(column, DeferredColumn):
raise MergeError(f"Cannot merge on DeferredColumn `{name}`.")
elif not isinstance(column, ScalarColumn):
raise MergeError(f"Cannot merge on column `{name}` of type {type(column)}.")
| meerkat-main | meerkat/ops/merge.py |
import asyncio
import concurrent
import functools
from typing import Any, Callable, Union
from tqdm.auto import tqdm
import meerkat as mk
async def callasync(fn: Callable, element: Any):
"""Call a function asynchronously.
Uses the `asyncio` library to call a function asynchronously.
"""
loop = asyncio.get_event_loop()
with concurrent.futures.ThreadPoolExecutor() as executor:
result = await loop.run_in_executor(executor, fn, element)
return result
def asasync(fn: Callable):
"""Decorator to make a function asynchronous."""
@functools.wraps(fn)
async def wrapper(element):
return await callasync(fn, element)
return wrapper
async def apply_function(fn: Callable, column: mk.Column):
"""Asynchronously apply a function to each element in a column. Run the
return value of this function through `asyncio.run()` to get the results.
Args:
fn: The async function to apply to each element.
column: The column to apply the function to.
"""
assert asyncio.iscoroutinefunction(fn), "Function must be async."
tasks = []
# for element in tqdm_asyncio(column, desc=f"Async execution of `{fn.__name__}`"):
for element in column:
tasks.append(fn(element))
results = await asyncio.gather(*tasks)
return results
def as_single_arg_fn(fn: Callable) -> Callable:
"""Convert a function that takes multiple arguments to a function that
takes a single argument."""
@functools.wraps(fn)
def wrapper(kwargs):
return fn(**kwargs)
return wrapper
async def amap(
data: Union[mk.DataFrame, mk.Column],
function: Callable,
pbar: bool = True,
max_concurrent: int = 100,
) -> Union[mk.DataFrame, mk.Column]:
"""Apply a function to each element in the column.
Args:
data: The column or dataframe to apply the function to.
function: The function to apply to each element in the column.
pbar: Whether to show a progress bar or not.
max_concurrent: The maximum number of concurrent tasks to run.
Returns:
A column or dataframe with the function applied to each element.
"""
# # Check if the function is async. If not, make it.
# if not asyncio.iscoroutinefunction(function):
# warnings.warn(
# f"Function {function} is not async. Automatically converting to async."
# " Consider making it async before calling `amap`."
# )
fn_name = function.__name__ if hasattr(function, "__name__") else str(function)
if isinstance(data, mk.Column):
# Run the function asynchronously on the column.
# Only run `max_concurrent` tasks at a time.
# Split the column into chunks of size `max_concurrent`.
chunks = [
data[i : i + max_concurrent] for i in range(0, len(data), max_concurrent)
]
# Synchonously apply the function to each chunk.
results = []
for chunk in tqdm(chunks, desc=f"Chunked execution of `{fn_name}`"):
results.append(await apply_function(asasync(function), chunk))
# Flatten the results.
results = [item for sublist in results for item in sublist]
# Create a new column with the results.
return mk.ScalarColumn(results)
elif isinstance(data, mk.DataFrame):
# Run the function asynchronously on the dataframe.
# Only run `max_concurrent` tasks at a time.
# Get the function parameter names.
import inspect
parameter_names = list(inspect.signature(function).parameters.keys())
# Restrict the dataframe to only the columns that are needed.
data = data[parameter_names]
# Split the dataframe into chunks of size `max_concurrent`.
chunks = [
data[i : i + max_concurrent] for i in range(0, len(data), max_concurrent)
]
# Synchonously apply the function to each chunk.
results = []
for chunk in tqdm(chunks, desc=f"Chunked execution of `{fn_name}`"):
results.append(
await apply_function(asasync(as_single_arg_fn(function)), chunk)
)
# Flatten the results.
results = [item for sublist in results for item in sublist]
# Create a new column with the results.
return mk.ScalarColumn(results)
else:
raise TypeError(f"Data must be a Column or DataFrame. Got {type(data)}.")
| meerkat-main | meerkat/ops/amap.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.