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: add `rate` and `eta` to mo.status.progress_bar (#426)

Myles Scolnick7a150aed75d2
diff --git a/frontend/package.json b/frontend/package.json
index a957652040..834cdaa2d9 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -58,6 +58,7 @@
"@storybook/addon-styling": "^1.3.7",
"@tanstack/react-table": "^8.10.7",
"@textea/json-viewer": "^3.2.3",
+ "@types/humanize-duration": "^3.27.3",
"@types/js-cookie": "^3.0.6",
"@types/jsdom": "^21.1.6",
"@types/react-grid-layout": "^1.3.5",
@@ -75,6 +76,7 @@
"htm": "^3.1.1",
"html-react-parser": "^5.0.7",
"html-to-image": "^1.11.11",
+ "humanize-duration": "^3.31.0",
"jotai": "^2.6.0",
"js-cookie": "^3.0.5",
"katex": "^0.16.9",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 7b83b42922..d199d2932b 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -143,6 +143,9 @@ dependencies:
'@textea/json-viewer':
specifier: ^3.2.3
+ '@types/humanize-duration':
+ specifier: ^3.27.3
+ version: 3.27.3
'@types/js-cookie':
specifier: ^3.0.6
version: 3.0.6
@@ -194,6 +197,9 @@ dependencies:
html-to-image:
specifier: ^1.11.11
version: 1.11.11
+ humanize-duration:
+ specifier: ^3.31.0
+ version: 3.31.0
jotai:
specifier: ^2.6.0
version: 2.6.0(@types/[email protected])([email protected])
@@ -6011,6 +6017,10 @@ packages:
'@types/node': 20.8.10
dev: true
+ resolution: {integrity: sha512-wiiiFYjnrYDJE/ujU7wS/NShqp12IKrejozjDtcejP0zYi+cjyjVcfZHwcFUDKVJ7tHGsmgeW2ED92ABIIjfpg==}
+ dev: false
+
resolution: {integrity: sha512-z/QT1XN4K4KYuslS23k62yDIDLwLFkzxOuMplDtObz0+y7VqJCaO2o+SPwHCvLFZh7xazvvoor2tA/hPz9ee7g==}
dev: true
@@ -10272,6 +10282,10 @@ packages:
engines: {node: '>=10.17.0'}
dev: true
+ resolution: {integrity: sha512-fRrehgBG26NNZysRlTq1S+HPtDpp3u+Jzdc/d5A4cEzOD86YLAkDaJyJg8krSdCi7CJ+s7ht3fwRj8Dl+Btd0w==}
+ dev: false
+
resolution: {integrity: sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==}
engines: {node: '>=0.10.0'}
diff --git a/frontend/src/plugins/layout/ProgressPlugin.tsx b/frontend/src/plugins/layout/ProgressPlugin.tsx
index 521ce6b046..5b831d8681 100644
--- a/frontend/src/plugins/layout/ProgressPlugin.tsx
+++ b/frontend/src/plugins/layout/ProgressPlugin.tsx
@@ -1,11 +1,13 @@
/* Copyright 2023 Marimo. All rights reserved. */
-import { PropsWithChildren } from "react";
+import React, { PropsWithChildren } from "react";
import { z } from "zod";
import { IStatelessPlugin, IStatelessPluginProps } from "../stateless-plugin";
import { renderHTML } from "../core/RenderHTML";
import { Progress } from "@/components/ui/progress";
import { Loader2Icon } from "lucide-react";
+import { clamp } from "@/utils/math";
+import humanizeDuration from "humanize-duration";
interface Data {
/**
@@ -25,6 +27,14 @@ interface Data {
* The total value of the progress bar.
*/
total?: number;
+ /**
+ * The estimated time remaining in seconds.
+ */
+ eta?: number;
+ /**
+ * The rate of progress in items per second.
+ */
+ rate?: number;
}
export class ProgressPlugin implements IStatelessPlugin<Data> {
@@ -35,6 +45,8 @@ export class ProgressPlugin implements IStatelessPlugin<Data> {
subtitle: z.string().optional(),
progress: z.union([z.number(), z.boolean()]),
total: z.number().optional(),
+ eta: z.number().optional(),
+ rate: z.number().optional(),
});
render(props: IStatelessPluginProps<Data>): JSX.Element {
@@ -47,9 +59,70 @@ export const ProgressComponent = ({
subtitle,
progress,
total,
+ eta,
+ rate,
}: PropsWithChildren<Data>): JSX.Element => {
const alignment =
typeof progress === "number" ? "items-start" : "items-center";
+
+ const renderProgress = () => {
+ // With a known total, show a progress bar.
+ if (typeof progress === "number" && total != null && total > 0) {
+ return (
+ <div className="flex gap-3 text-sm text-muted-foreground items-baseline">
+ <Progress value={clampProgress((progress / total) * 100)} />
+ <span className="flex-shrink-0">
+ {progress} / {total}
+ </span>
+ </div>
+ );
+ }
+
+ // With an unknown total, show a spinner.
+ return (
+ <Loader2Icon className="w-12 h-12 animate-spin text-primary mx-auto" />
+ );
+ };
+
+ const renderMeta = () => {
+ const hasCompleted =
+ typeof progress === "number" && total != null && progress >= total;
+
+ const elements: React.ReactNode[] = [];
+ if (rate) {
+ elements.push(
+ <span key="rate">{rate} iter/s</span>,
+ <span key="spacer-rate">&middot;</span>
+ );
+ }
+
+ if (!hasCompleted && eta) {
+ elements.push(
+ <span key="eta">ETA {prettyTime(eta)}</span>,
+ <span key="spacer-eta">&middot;</span>
+ );
+ }
+
+ if (hasCompleted && rate) {
+ const totalTime = progress / rate;
+ elements.push(
+ <span key="completed">Total time {prettyTime(totalTime)}</span>,
+ <span key="spacer-completed">&middot;</span>
+ );
+ }
+
+ // pop the last spacer
+ elements.pop();
+
+ if (elements.length > 0) {
+ return (
+ <div className="flex gap-2 text-muted-foreground text-sm">
+ {elements}
+ </div>
+ );
+ }
+ };
+
return (
<div className={`flex flex-col ${alignment} max-w-sm p-6 mx-auto`}>
{title && (
@@ -62,25 +135,38 @@ export const ProgressComponent = ({
{renderHTML({ html: subtitle })}
</div>
)}
- <div className="mt-2 w-full">
- {typeof progress === "number" && total != null && total > 0 ? (
- <div className="flex gap-3 text-sm text-muted-foreground items-baseline">
- <Progress value={clampProgress((progress / total) * 100)} />
- <span className="flex-shrink-0">
- {progress} / {total}
- </span>
- </div>
- ) : (
- <Loader2Icon className="w-12 h-12 animate-spin text-primary mx-auto" />
- )}
+ <div className="mt-2 w-full flex flex-col gap-1">
+ {renderProgress()}
+ {renderMeta()}
</div>
</div>
);
};
-function clamp(value: number, min: number, max: number): number {
- return Math.min(Math.max(value, min), max);
-}
function clampProgress(progress: number): number {
return clamp(progress, 0, 100);
}
+
+const shortDuration = humanizeDuration.humanizer({
+ language: "shortEn",
+ languages: {
+ shortEn: {
+ y: () => "y",
+ mo: () => "mo",
+ w: () => "w",
+ d: () => "d",
+ h: () => "h",
+ m: () => "m",
+ s: () => "s",
+ ms: () => "ms",
+ },
+ },
+});
+export function prettyTime(seconds: number): string {
+ return shortDuration(seconds * 1000, {
+ language: "shortEn",
+ largest: 2,
+ spacer: "",
+ maxDecimalPoints: 2,
+ });
+}
diff --git a/frontend/src/plugins/layout/__test__/ProgressPlugin.test.ts b/frontend/src/plugins/layout/__test__/ProgressPlugin.test.ts
new file mode 100644
index 0000000000..ee0b6b49f9
--- /dev/null
+++ b/frontend/src/plugins/layout/__test__/ProgressPlugin.test.ts
@@ -0,0 +1,26 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { expect, test } from "vitest";
+import { prettyTime } from "../ProgressPlugin";
+
+// examples of expected output
+test("prettyTime", () => {
+ // exact
+ expect(prettyTime(0)).toMatchInlineSnapshot('"0s"');
+ expect(prettyTime(1)).toMatchInlineSnapshot('"1s"');
+ expect(prettyTime(60)).toMatchInlineSnapshot('"1m"');
+ expect(prettyTime(60 * 60)).toMatchInlineSnapshot('"1h"');
+ expect(prettyTime(60 * 60 * 24)).toMatchInlineSnapshot('"1d"');
+
+ // decimal
+ expect(prettyTime(0.5)).toMatchInlineSnapshot('"0.5s"');
+ expect(prettyTime(1.5)).toMatchInlineSnapshot('"1.5s"');
+ expect(prettyTime(60 * 1.5)).toMatchInlineSnapshot('"1m, 30s"');
+ expect(prettyTime(60 * 60 * 1.5)).toMatchInlineSnapshot('"1h, 30m"');
+ expect(prettyTime(60 * 60 * 24 * 1.5)).toMatchInlineSnapshot('"1d, 12h"');
+
+ // edge cases
+ expect(prettyTime(0)).toMatchInlineSnapshot('"0s"');
+ expect(prettyTime(0.0001)).toMatchInlineSnapshot('"0s"');
+ expect(prettyTime(0.001)).toMatchInlineSnapshot('"0s"');
+ expect(prettyTime(0.01)).toMatchInlineSnapshot('"0.01s"');
+});
diff --git a/frontend/src/stories/progress-component.stories.tsx b/frontend/src/stories/progress-component.stories.tsx
index 06a536d0a8..01b604a4ac 100644
--- a/frontend/src/stories/progress-component.stories.tsx
+++ b/frontend/src/stories/progress-component.stories.tsx
@@ -24,6 +24,34 @@ Default.args = {
total: 10,
};
+export const WithRate = Template.bind({});
+WithRate.args = {
+ title: "Parsing documents",
+ subtitle: "This may take a few seconds",
+ progress: 4,
+ total: 10,
+ rate: 2,
+};
+
+export const WithEta = Template.bind({});
+WithEta.args = {
+ title: "Parsing documents",
+ subtitle: "This may take a few seconds",
+ progress: 4,
+ total: 10,
+ eta: 20,
+};
+
+export const WithRateAndEta = Template.bind({});
+WithRateAndEta.args = {
+ title: "Parsing documents",
+ subtitle: "This may take a few seconds",
+ progress: 4,
+ total: 10,
+ rate: 2,
+ eta: 10,
+};
+
export const Spinner = Template.bind({});
Spinner.args = {
title: "Loading model",
diff --git a/frontend/src/utils/math.ts b/frontend/src/utils/math.ts
new file mode 100644
index 0000000000..810c32c2aa
--- /dev/null
+++ b/frontend/src/utils/math.ts
@@ -0,0 +1,5 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+
+export function clamp(value: number, min: number, max: number) {
+ return Math.min(Math.max(value, min), max);
+}
diff --git a/marimo/_plugins/stateless/status/_progress.py b/marimo/_plugins/stateless/status/_progress.py
index 49f74780e9..948c05810e 100644
--- a/marimo/_plugins/stateless/status/_progress.py
+++ b/marimo/_plugins/stateless/status/_progress.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import contextlib
+import time
from collections.abc import Collection
from typing import Iterable, Iterator, Optional, TypeVar
@@ -26,6 +27,8 @@ class _Progress(Html):
title: Optional[str],
subtitle: Optional[str],
total: Optional[int],
+ show_rate: bool,
+ show_eta: bool,
) -> None:
self.title = title
self.subtitle = subtitle
@@ -34,6 +37,9 @@ class _Progress(Html):
self.closed = False
# We show a loading spinner if total not known
self.loading_spinner = total is None
+ self.show_rate = show_rate
+ self.show_eta = show_eta
+ self.start_time = time.time()
super().__init__(self._get_text())
def __del__(self) -> None:
@@ -100,16 +106,49 @@ class _Progress(Html):
# 'progress' is True is we don't know the total,
# which shows a loading spinner
"progress": True if self.loading_spinner else self.current,
+ "rate": self._get_rate(),
+ "eta": self._get_eta(),
}
),
)
+ def _get_rate(self) -> Optional[float]:
+ if self.show_rate:
+ diff = time.time() - self.start_time
+ if diff == 0:
+ return None
+ rate = self.current / diff
+ return round(rate, 2)
+ else:
+ return None
+
+ def _get_eta(self) -> Optional[float]:
+ if self.show_eta and self.total is not None:
+ rate = self._get_rate()
+ if rate is not None and rate > 0:
+ return round((self.total - self.current) / rate, 2)
+ else:
+ return None
+ else:
+ return None
+
class ProgressBar(_Progress):
def __init__(
- self, title: str | None, subtitle: str | None, total: int
+ self,
+ title: str | None,
+ subtitle: str | None,
+ total: int,
+ show_rate: bool,
+ show_eta: bool,
) -> None:
- super().__init__(title=title, subtitle=subtitle, total=total)
+ super().__init__(
+ title=title,
+ subtitle=subtitle,
+ total=total,
+ show_rate=show_rate,
+ show_eta=show_eta,
+ )
def update(
self,
@@ -127,7 +166,13 @@ class Spinner(_Progress):
"""A spinner output representing a loading state"""
def __init__(self, title: str | None, subtitle: str | None) -> None:
- super().__init__(title=title, subtitle=subtitle, total=None)
+ super().__init__(
+ title=title,
+ subtitle=subtitle,
+ total=None,
+ show_rate=False,
+ show_eta=False,
+ )
def update(
self, title: str | None = None, subtitle: str | None = None
@@ -197,6 +242,8 @@ def progress_bar(
subtitle: Optional[str] = None,
completion_title: Optional[str] = None,
completion_subtitle: Optional[str] = None,
+ show_rate: bool = True,
+ show_eta: bool = True,
) -> Iterable[S | int]:
"""Iterate over a collection and show a progress bar
@@ -217,6 +264,8 @@ def progress_bar(
- `subtitle`: optional subtitle
- `completion_title`: optional title to show during completion
- `completion_subtitle`: optional subtitle to show during completion
+ - `show_rate`: if True, show the rate of progress (items per second)
+ - `show_eta`: if True, show the estimated time of completion
**Returns.**
@@ -228,7 +277,13 @@ def progress_bar(
else:
total = len(collection)
step = 1
- progress = ProgressBar(title=title, subtitle=subtitle, total=total)
+ progress = ProgressBar(
+ title=title,
+ subtitle=subtitle,
+ total=total,
+ show_rate=show_rate,
+ show_eta=show_eta,
+ )
output.append(progress)
for item in collection:
yield item
diff --git a/marimo/_plugins/stateless/status/test_progress.py b/marimo/_plugins/stateless/status/test_progress.py
new file mode 100644
index 0000000000..dd4874d0c3
--- /dev/null
+++ b/marimo/_plugins/stateless/status/test_progress.py
@@ -0,0 +1,95 @@
+# Copyright 2023 Marimo. All rights reserved.
+import time
+from typing import Any
+from unittest.mock import patch
+
+import pytest
+
+from marimo._plugins.stateless.status._progress import _Progress
+
+
+# Test initialization
+def test_progress_init() -> None:
+ progress = _Progress(
+ title="Test",
+ subtitle="Running",
+ total=100,
+ show_rate=True,
+ show_eta=True,
+ )
+ assert progress.title == "Test"
+ assert progress.subtitle == "Running"
+ assert progress.total == 100
+ assert progress.current == 0
+ assert progress.closed is False
+ assert progress.loading_spinner is False
+ assert progress.show_rate is True
+ assert progress.show_eta is True
+ # sleep 10ms
+ time.sleep(0.01)
+ rate = progress._get_rate()
+ assert rate == 0.0
+ eta = progress._get_eta()
+ assert eta is None
+
+
+# Test update_progress method
+@patch("marimo._runtime.output._output.flush")
+def test_update_progress(_mock_flush: Any) -> None:
+ progress = _Progress(
+ title="Test",
+ subtitle="Running",
+ total=10000000,
+ show_rate=True,
+ show_eta=True,
+ )
+ # sleep 100ms
+ time.sleep(0.1)
+ progress.update_progress(
+ increment=10, title="Updated", subtitle="Still Running"
+ )
+ assert progress.current == 10
+ assert progress.title == "Updated"
+ assert progress.subtitle == "Still Running"
+ rate = progress._get_rate()
+ assert rate is not None and rate > 0.0
+ eta = progress._get_eta()
+ assert eta is not None and eta > 0.0
+
+
+# Test update_progress without arguments
+@patch("marimo._runtime.output._output.flush")
+def test_update_progress_no_args(_mock_flush: Any) -> None:
+ progress = _Progress(
+ title="Test",
+ subtitle="Running",
+ total=100,
+ show_rate=False,
+ show_eta=False,
+ )
+ # sleep 100ms
+ time.sleep(0.1)
+ progress.update_progress()
+ assert progress.current == 1
+ assert progress.title == "Test"
+ assert progress.subtitle == "Running"
+ rate = progress._get_rate()
+ assert rate is None
+ eta = progress._get_eta()
+ assert eta is None
+
+
+# Test update_progress with closed progress
+@patch("marimo._runtime.output._output.flush")
+def test_update_progress_closed(_mock_flush: Any) -> None:
+ progress = _Progress(
+ title="Test",
+ subtitle="Running",
+ total=100,
+ show_rate=True,
+ show_eta=True,
+ )
+ progress.close()
+ assert progress.closed is True
+ with pytest.raises(RuntimeError):
+ progress.update_progress()
diff --git a/marimo/_smoke_tests/status.py b/marimo/_smoke_tests/status.py
index 1bbaf88553..8e2d2fdeaf 100644
--- a/marimo/_smoke_tests/status.py
+++ b/marimo/_smoke_tests/status.py
@@ -1,7 +1,6 @@
-# Copyright 2023 Marimo. All rights reserved.
import marimo
-__generated_with = "0.1.24"
+__generated_with = "0.1.63"
app = marimo.App()
@@ -21,6 +20,15 @@ def __(mo, time):
return
+def __(mo, time):
+ for _ in mo.status.progress_bar(
+ range(10), title="Loading", subtitle="Please wait", show_eta=True, show_rate=True
+ ):
+ time.sleep(0.5)
+ return
+
+
@app.cell
def __(mo, time):
with mo.status.spinner(title="Loading...", remove_on_exit=True) as _spinner: