Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

improvement: improve table performance by using virutal file for pandas data (#217)

Myles Scolnick489a9b668ff9
diff --git a/examples/dashboards/movies.py b/examples/dashboards/movies.py
new file mode 100644
index 0000000000..276bde6805
--- /dev/null
+++ b/examples/dashboards/movies.py
@@ -0,0 +1,406 @@
+import marimo
+
+__generated_with = "0.1.30"
+app = marimo.App(width="full")
+
+
+def __(
+ button_00s,
+ button_10s,
+ button_80s,
+ button_90s,
+ end_date,
+ mo,
+ start_date,
+):
+ _range = mo.md(f"{start_date} - {end_date}")
+
+ mo.hstack(
+ [
+ _range,
+ mo.hstack(
+ [
+ mo.md("Quick decade:"),
+ button_80s,
+ button_90s,
+ button_00s,
+ button_10s,
+ ]
+ ),
+ ]
+ )
+ return
+
+
+def __(mo, pd, set_end_date, set_start_date):
+ def decade_button(decade):
+ s = pd.to_datetime(f"{decade}-01-01")
+ e = pd.to_datetime(f"{decade + 10}-01-01")
+
+ def handle_click(v):
+ set_start_date(s)
+ set_end_date(e)
+ return 1
+
+ return mo.ui.button(
+ label=f"{decade}s",
+ on_click=handle_click,
+ )
+
+
+ button_80s = decade_button(1980)
+ button_90s = decade_button(1990)
+ button_00s = decade_button(2000)
+ button_10s = decade_button(2010)
+ return button_00s, button_10s, button_80s, button_90s, decade_button
+
+
+def __(mo, previous_end_date, previous_start_date):
+ mo.md(
+ f"""
+ > Compared to: {previous_start_date.strftime("%Y-%m-%d")} - {previous_end_date.strftime("%Y-%m-%d")}
+ """
+ )
+ return
+
+
+def __(get_end_date, get_start_date, mo, pd, set_end_date, set_start_date):
+ start_date = mo.ui.date(
+ label="Start Date",
+ value=get_start_date().strftime("%Y-%m-%d"),
+ on_change=lambda x: set_start_date(pd.to_datetime(x)),
+ )
+ end_date = mo.ui.date(
+ label="End Date",
+ value=get_end_date().strftime("%Y-%m-%d"),
+ on_change=lambda x: set_end_date(pd.to_datetime(x)),
+ )
+ return end_date, start_date
+
+
+def __(
+ filtered_movies,
+ get_average_budget,
+ get_average_gross,
+ get_average_rating,
+ get_average_runtime,
+ mo,
+ previous_movies,
+):
+ mo.stop(len(filtered_movies) == 0, "")
+
+ previous_total_movies_count = len(previous_movies)
+ previous_total_movies_change_rate = (
+ (len(filtered_movies) - previous_total_movies_count)
+ / previous_total_movies_count
+ if previous_total_movies_count > 0
+ else 0
+ )
+ total_movies = mo.stat(
+ label="Total Movies",
+ bordered=True,
+ caption=f"{previous_total_movies_change_rate:.0%}",
+ direction="increase"
+ if previous_total_movies_change_rate > 0
+ else "decrease",
+ value=f"{len(filtered_movies):,.0f}",
+ )
+
+ gross_current, gross_previous, gross_rate = get_average_gross(
+ filtered_movies, previous_movies
+ )
+ gross_stat = mo.stat(
+ label="Average Gross",
+ bordered=True,
+ caption=f"{gross_rate:.0%}",
+ direction="increase" if gross_rate > 0 else "decrease",
+ value=f"${gross_current:,.0f}",
+ )
+
+ budget_current, budget_previous, budget_rate = get_average_budget(
+ filtered_movies, previous_movies
+ )
+ budget_stat = mo.stat(
+ label="Average Budget",
+ bordered=True,
+ caption=f"{budget_rate:.0%}",
+ direction="increase" if budget_rate > 0 else "decrease",
+ value=f"${budget_current:,.0f}",
+ )
+
+ runtime_current, runtime_previous, runtime_rate = get_average_runtime(
+ filtered_movies, previous_movies
+ )
+ runtime_stat = mo.stat(
+ label="Average Runtime",
+ bordered=True,
+ caption=f"{runtime_rate:.0%}",
+ direction="increase" if runtime_rate > 0 else "decrease",
+ value=f"{runtime_current:,.0f} min",
+ )
+
+ rating_current, rating_previous, rating_rate = get_average_rating(
+ filtered_movies, previous_movies
+ )
+ average_rating = mo.stat(
+ label="Average Rating",
+ bordered=True,
+ caption=f"{rating_rate:.0%}",
+ direction="increase" if rating_rate > 0 else "decrease",
+ value=f"{rating_current:.1f}",
+ )
+
+ mo.hstack(
+ [total_movies, gross_stat, budget_stat, runtime_stat, average_rating],
+ widths="equal",
+ gap=1,
+ )
+ return (
+ average_rating,
+ budget_current,
+ budget_previous,
+ budget_rate,
+ budget_stat,
+ gross_current,
+ gross_previous,
+ gross_rate,
+ gross_stat,
+ previous_total_movies_change_rate,
+ previous_total_movies_count,
+ rating_current,
+ rating_previous,
+ rating_rate,
+ runtime_current,
+ runtime_previous,
+ runtime_rate,
+ runtime_stat,
+ total_movies,
+ )
+
+
+def __(filtered_movies, mo):
+ mo.ui.table(filtered_movies, selection=None)
+ return
+
+
+def __(alt, filtered_movies, mo):
+ # chart of rating by budget
+ _chart = (
+ alt.Chart(filtered_movies)
+ .mark_circle()
+ .encode(
+ x="Production_Budget",
+ y="IMDB_Rating",
+ color="Major_Genre",
+ tooltip=[
+ "Title",
+ "Production_Budget",
+ "Worldwide_Gross",
+ "IMDB_Rating",
+ "Major_Genre",
+ ],
+ )
+ )
+ chart = mo.ui.altair_chart(_chart)
+ chart
+ return chart,
+
+
+def __(
+ chart,
+ get_average_budget,
+ get_average_gross,
+ get_average_rating,
+ get_average_runtime,
+ mo,
+):
+ mo.stop(len(chart.value) == 0, mo.callout("Select data to view stats."))
+
+ _total_movies = mo.stat(
+ label="Total Movies",
+ value=f"{len(chart.value):,.0f}",
+ )
+
+ _gross_current, _, _ = get_average_gross(chart.value, chart.value)
+ _gross_stat = mo.stat(
+ label="Average Gross",
+ value=f"${_gross_current:,.0f}",
+ )
+
+ _budget_current, _, _ = get_average_budget(chart.value, chart.value)
+ _budget_stat = mo.stat(
+ label="Average Budget",
+ value=f"${_budget_current:,.0f}",
+ )
+
+ _runtime_current, _, _ = get_average_runtime(chart.value, chart.value)
+ _runtime_stat = mo.stat(
+ label="Average Runtime",
+ value=f"{_runtime_current:,.0f} min",
+ )
+
+ _rating_current, _, _ = get_average_rating(chart.value, chart.value)
+ _average_rating = mo.stat(
+ label="Average Rating",
+ value=f"{_rating_current:.1f}",
+ )
+
+ mo.hstack(
+ [_total_movies, _gross_stat, _budget_stat, _runtime_stat, _average_rating],
+ widths="equal",
+ gap=1,
+ )
+ return
+
+
+def __(alt, filtered_movies, mo):
+ # chart of ratings by genre
+ # colored by decade
+ _bar_chart = (
+ alt.Chart(filtered_movies)
+ .mark_bar()
+ .encode(
+ x=alt.X("Major_Genre", sort="-y"),
+ y="count()",
+ color=alt.Color("Release_Date", scale=alt.Scale(scheme="viridis")),
+ tooltip=["Major_Genre", "count()"],
+ )
+ )
+ bar_chart = mo.ui.altair_chart(_bar_chart)
+ bar_chart
+ return bar_chart,
+
+
+def __(datetime):
+ def get_average_budget(df, previous):
+ current = df["US_Gross"].mean()
+ previous = previous["US_Gross"].mean()
+ rate = (current - previous) / previous
+ return (current, previous, rate)
+
+
+ def get_average_gross(df, previous):
+ current = df["Worldwide_Gross"].mean()
+ previous = previous["Worldwide_Gross"].mean()
+ rate = (current - previous) / previous
+ return (current, previous, rate)
+
+
+ def get_average_runtime(df, previous):
+ current = df["Running_Time_min"].mean()
+ previous = previous["Running_Time_min"].mean()
+ rate = (current - previous) / previous
+ return (current, previous, rate)
+
+
+ def get_average_rating(df, previous):
+ current = df["IMDB_Rating"].mean()
+ previous = previous["IMDB_Rating"].mean()
+ rate = (current - previous) / previous
+ return (current, previous, rate)
+
+
+ def get_previous_date_range(start_date, end_date):
+ delta = end_date - start_date
+ return (
+ (start_date - datetime.timedelta(days=delta.days)),
+ (end_date - datetime.timedelta(days=delta.days)),
+ )
+
+
+ def format_date(date):
+ return date.strftime("%Y-%m-%d")
+ return (
+ format_date,
+ get_average_budget,
+ get_average_gross,
+ get_average_rating,
+ get_average_runtime,
+ get_previous_date_range,
+ )
+
+
+def __():
+ import marimo as mo
+ import vega_datasets as data
+ import time
+ import pandas as pd
+ import datetime
+ import altair as alt
+ return alt, data, datetime, mo, pd, time
+
+
+def __(data, pd):
+ movies = data.data.movies()
+
+ # convert to date
+ movies["Release_Date"] = pd.to_datetime(movies["Release_Date"])
+ return movies,
+
+
+def __(mo, pd):
+ # min = movies["Release_Date"].min()
+ # max = movies["Release_Date"].max()
+ min = "2010-01-01"
+ max = "2021-01-01"
+ get_start_date, set_start_date = mo.state(pd.to_datetime(min))
+ get_end_date, set_end_date = mo.state(pd.to_datetime(max))
+ return (
+ get_end_date,
+ get_start_date,
+ max,
+ min,
+ set_end_date,
+ set_start_date,
+ )
+
+
+def __(end_date, get_previous_date_range, movies, pd, start_date):
+ start = pd.to_datetime(start_date.value)
+ end = pd.to_datetime(end_date.value)
+ filtered_movies = movies[
+ (movies["Release_Date"] >= start) & (movies["Release_Date"] <= end)
+ ]
+ try:
+ previous_start_date, previous_end_date = get_previous_date_range(
+ start, end
+ )
+ previous_movies = movies[
+ (movies["Release_Date"] >= previous_start_date)
+ & (movies["Release_Date"] <= previous_end_date)
+ ]
+ except:
+ previous_start_date = start
+ previous_end_date = end
+ previous_movies = filtered_movies
+ return (
+ end,
+ filtered_movies,
+ previous_end_date,
+ previous_movies,
+ previous_start_date,
+ start,
+ )
+
+
+def __():
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/frontend/package.json b/frontend/package.json
index 8f3892ccd8..50450b77ee 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -90,6 +90,7 @@
"tailwindcss-animate": "^1.0.7",
"timestring": "^7.0.0",
"vega-lite": "^5.15.0",
+ "vega-loader": "^4.5.1",
"vscode-languageserver-protocol": "^3.17.5",
"web-vitals": "^3.5.0",
"zod": "^3.22.2"
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index a702a81157..eee02cb1db 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -242,6 +242,9 @@ dependencies:
vega-lite:
specifier: ^5.15.0
version: 5.15.0([email protected])
+ vega-loader:
+ specifier: ^4.5.1
+ version: 4.5.1
vscode-languageserver-protocol:
specifier: ^3.17.5
version: 3.17.5
diff --git a/frontend/src/hooks/useAsyncData.ts b/frontend/src/hooks/useAsyncData.ts
new file mode 100644
index 0000000000..7225d763c4
--- /dev/null
+++ b/frontend/src/hooks/useAsyncData.ts
@@ -0,0 +1,51 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { DependencyList, useState, useEffect } from "react";
+
+/**
+ * A hook that loads data asynchronously.
+ * Handles loading and error states, and prevents race conditions.
+ */
+export function useAsyncData<T>(
+ loader: () => Promise<T>,
+ deps: DependencyList
+): {
+ data: T | undefined;
+ loading: boolean;
+ error: Error | undefined;
+} {
+ const [data, setData] = useState<T | undefined>(undefined);
+ const [loading, setLoading] = useState<boolean>(false);
+ const [error, setError] = useState<Error | undefined>(undefined);
+
+ useEffect(() => {
+ let isCancelled = false;
+ setLoading(true);
+ loader()
+ .then((data) => {
+ if (isCancelled) {
+ return;
+ }
+ setData(data);
+ setError(undefined);
+ })
+ .catch((error_) => {
+ if (isCancelled) {
+ return;
+ }
+ setError(error_);
+ })
+ .finally(() => {
+ if (isCancelled) {
+ return;
+ }
+ setLoading(false);
+ });
+
+ return () => {
+ isCancelled = true;
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, deps);
+
+ return { data, loading, error };
+}
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index c3817b20da..81beb41c62 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -1,21 +1,25 @@
/* Copyright 2023 Marimo. All rights reserved. */
import { useMemo } from "react";
import { z } from "zod";
+// @ts-expect-error - no types
+import { loader as createLoader, read } from "vega-loader";
import { IPlugin, IPluginProps } from "@/plugins/types";
import { DataTable } from "../../components/data-table/data-table";
import { generateColumns } from "../../components/data-table/columns";
import { Labeled } from "./common/labeled";
+import { useAsyncData } from "@/hooks/useAsyncData";
+import { Alert, AlertTitle } from "@/components/ui/alert";
/**
* Arguments for a data table
*
* @param label - a label of the table
- * @param data - the data to display
+ * @param data - the data to display, or a URL to load the data from
*/
interface Data<T> {
label: string | null;
- data: T[];
+ data: T[] | string;
pagination: boolean;
selection: "single" | "multi" | null;
}
@@ -23,21 +27,34 @@ interface Data<T> {
// Value is selection, but it is not currently exposed to the user
type S = Array<string | number>;
+const loader = createLoader();
+
export class DataTablePlugin implements IPlugin<S, Data<unknown>> {
tagName = "marimo-table";
validator = z.object({
initialValue: z.array(z.number()),
label: z.string().nullable(),
- data: z.array(z.object({}).passthrough()),
+ data: z.union([z.string(), z.array(z.object({}).passthrough())]),
pagination: z.boolean().default(false),
selection: z.enum(["single", "multi"]).nullable().default(null),
});
render(props: IPluginProps<S, Data<unknown>>): JSX.Element {
+ if (typeof props.data.data === "string") {
+ return (
+ <LoadingDataTableComponent
+ {...props.data}
+ data={props.data.data}
+ value={props.value}
+ setValue={props.setValue}
+ />
+ );
+ }
return (
<DataTableComponent
{...props.data}
+ data={props.data.data}
value={props.value}
setValue={props.setValue}
/>
@@ -50,6 +67,34 @@ interface DataTableProps extends Data<unknown> {
setValue: (value: S) => void;
}
+const LoadingDataTableComponent = (
+ props: DataTableProps & { data: string }
+) => {
+ const { data, loading, error } = useAsyncData<unknown[]>(() => {
+ return loader.load(props.data).then((csvData: string) => {
+ // csv -> json
+ return read(csvData, { type: "csv", parse: "auto" });
+ });
+ }, [props.data]);
+
+ if (loading && !data) {
+ return null;
+ }
+
+ if (error) {
+ return (
+ <Alert variant="destructive">
+ <AlertTitle>Error</AlertTitle>
+ <div className="text-md">
+ {error.message || "An unknown error occurred"}
+ </div>
+ </Alert>
+ );
+ }
+
+ return <DataTableComponent {...props} data={data || []} />;
+};
+
const DataTableComponent = ({
label,
data,
@@ -57,7 +102,9 @@ const DataTableComponent = ({
selection,
value,
setValue,
-}: DataTableProps): JSX.Element => {
+}: DataTableProps & {
+ data: unknown[];
+}): JSX.Element => {
const columns = useMemo(
() => generateColumns(data, selection),
[data, selection]
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index 7fa59754d2..5dea25b3a0 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -14,6 +14,7 @@ from typing import (
cast,
)
+import marimo._output.data.data as mo_data
from marimo import _loggers
from marimo._dependencies.dependencies import DependencyManager
from marimo._output.mime import MIME
@@ -142,7 +143,8 @@ def _normalize_data(data: TableData) -> JSONType:
import pandas as pd
if isinstance(data, pd.DataFrame):
- return data.to_dict("records") # type: ignore
+ vf = mo_data.csv(data)
+ return vf.url
# Assert that data is a list
if not isinstance(data, (list, tuple)):
diff --git a/marimo/_plugins/ui/_impl/test_table.py b/marimo/_plugins/ui/_impl/test_table.py
index df0c212496..da30739da5 100644
--- a/marimo/_plugins/ui/_impl/test_table.py
+++ b/marimo/_plugins/ui/_impl/test_table.py
@@ -2,9 +2,15 @@
from typing import Any
from marimo._plugins.ui._impl.table import TableData, _normalize_data
+from marimo._runtime.conftest import MockedKernel
+from marimo._runtime.runtime import ExecutionContext
def test_normalize_data() -> None:
+ # Create kernel and give the execution context an existing cell
+ mocked = MockedKernel()
+ mocked.k.execution_context = ExecutionContext("test_cell_id", False)
+
data: TableData
# Test with list of integers
@@ -44,11 +50,8 @@ def test_normalize_data() -> None:
data = pd.DataFrame({"column1": [1, 2, 3], "column2": ["a", "b", "c"]})
result = _normalize_data(data)
- assert result == [
- {"column1": 1, "column2": "a"},
- {"column1": 2, "column2": "b"},
- {"column1": 3, "column2": "c"},
- ]
+ assert isinstance(result, str)
+ assert result.endswith(".csv")
except ImportError:
pass
diff --git a/marimo/_runtime/conftest.py b/marimo/_runtime/conftest.py
index 25fe978321..2f10cbc30a 100644
--- a/marimo/_runtime/conftest.py
+++ b/marimo/_runtime/conftest.py
@@ -52,17 +52,19 @@ class MockedKernel:
stderr=self.stderr, # type: ignore
)
+ def __del__(self) -> None:
+ # have to teardown the runtime context because it's a global
+ get_context()._kernel = None
+ get_context()._ui_element_registry = None
+ get_context()._stream = None
+ get_context()._initialized = False
+
# fixture that provides a kernel (and tears it down)
@pytest.fixture
def k() -> Generator[Kernel, None, None]:
mocked = MockedKernel()
yield mocked.k
- # have to teardown the runtime context because it's a global
- get_context()._kernel = None
- get_context()._ui_element_registry = None
- get_context()._stream = None
- get_context()._initialized = False
# fixture that wraps a kernel and other mocked objects
@@ -70,11 +72,6 @@ def k() -> Generator[Kernel, None, None]:
def mocked_kernel() -> Generator[MockedKernel, None, None]:
mocked = MockedKernel()
yield mocked
- # have to teardown the runtime context because it's a global
- get_context()._kernel = None
- get_context()._ui_element_registry = None
- get_context()._stream = None
- get_context()._initialized = False
# Factory to create ExecutionRequests and abstract away cell ID