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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
examples: add huggingface examples (#2792)
Myles Scolnick4c20bbcf84a2
diff --git a/examples/third_party/huggingface/README.md b/examples/third_party/huggingface/README.mdnew file mode 100644index 0000000000..bc53583fda--- /dev/null+++ b/examples/third_party/huggingface/README.md@@ -0,0 +1,29 @@+# HuggingFace 📦++These examples showcase how to use HuggingFace's models in marimo.++- You can find a list of these models [here](https://huggingface.co/models).+- These examples are easily deployable on [HuggingFace's Spaces](https://huggingface.co/new-space?template=marimo-team%2Fmarimo-app-template). Or check out our templates:+ - [Basic application template](https://huggingface.co/spaces/marimo-team/marimo-app-template/tree/main)+ - [Chatbot template](https://huggingface.co/spaces/marimo-team/marimo-chatbot-template/tree/main)+ - [Text-to-image template](https://huggingface.co/spaces/marimo-team/marimo-text-to-image-template/tree/main)++> [!TIP]+> Submit a+> [pull request](https://github.com/marimo-team/marimo/pulls) to add an example!++## Running examples++The requirements of each notebook are serialized in them as a top-level+comment. Here are the steps to open an example notebook:++1. [Install marimo](https://docs.marimo.io/getting_started/index.html#installation)+2. [Install `uv`](https://github.com/astral-sh/uv/?tab=readme-ov-file#installation)+3. Open an example with `marimo edit --sandbox <notebook.py>`.++> [!TIP]+> The [`--sandbox` flag](https://docs.marimo.io/guides/editor_features/package_management.html) opens the notebook in an isolated virtual environment,+> automatically installing the notebook's dependencies 📦++You can also open notebooks without `uv`, with just `marimo edit <notebook.py>`;+however, you'll need to install the requirements yourself.diff --git a/examples/third_party/huggingface/chatbot.py b/examples/third_party/huggingface/chatbot.pynew file mode 100644index 0000000000..c57c0fadfe--- /dev/null+++ b/examples/third_party/huggingface/chatbot.py@@ -0,0 +1,160 @@+# /// script+# requires-python = ">=3.12"+# dependencies = [+# "huggingface-hub==0.26.2",+# "marimo",+# ]+# ///++import marimo++__generated_with = "0.9.14"+app = marimo.App(width="medium")+++def __():+ import marimo as mo+ import os+ from huggingface_hub import InferenceClient+ return InferenceClient, mo, os+++def __():+ MODEL_NAME = "HuggingFaceH4/zephyr-7b-beta"+ return (MODEL_NAME,)++[email protected](hide_code=True)+def __(MODEL_NAME, mo):+ mo.md(f"""+ # Chat with **{MODEL_NAME}**+ """)+ return+++def __(max_tokens, mo, system_message, temperature, top_p):+ mo.hstack(+ [+ system_message,+ mo.vstack([temperature, top_p, max_tokens], align="end"),+ ],+ )+ return+++def __(mo, respond):+ chat = mo.ui.chat(+ model=respond,+ prompts=["Tell me a joke.", "What is the square root of {{number}}?"],+ )+ chat+ return (chat,)+++def __(InferenceClient, MODEL_NAME, os):+ """+ For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.26.2/en/guides/inference+ """++ hf_token = os.environ.get("HF_TOKEN")+ if not hf_token:+ print("HF_TOKEN not set, may have limited access.")++ client = InferenceClient(+ MODEL_NAME,+ token=hf_token,+ )+ return client, hf_token+++def __(client, mo):+ # Create UI controls+ system_message = mo.ui.text_area(+ value="You are a friendly Chatbot.",+ label="System message",+ )+ max_tokens = mo.ui.slider(+ start=1,+ stop=2048,+ value=512,+ step=1,+ label="Max new tokens",+ show_value=True,+ )+ temperature = mo.ui.slider(+ start=0.1,+ stop=4.0,+ value=0.7,+ step=0.1,+ label="Temperature",+ show_value=True,+ )+ top_p = mo.ui.slider(+ start=0.1,+ stop=1.0,+ value=0.95,+ step=0.05,+ label="Top-p (nucleus sampling)",+ show_value=True,+ )++ # Add more configuration options if needed.+++ # Create chat callback+ def respond(messages: list[mo.ai.ChatMessage], config):+ chat_messages = [{"role": "system", "content": system_message.value}]++ for message in messages:+ parts = []+ # Add text+ parts.append({"type": "text", "text": message.content})++ # Add attachments+ if message.attachments:+ for attachment in message.attachments:+ content_type = attachment.content_type or ""+ # This example only supports image attachments+ if content_type.startswith("image"):+ parts.append(+ {+ "type": "image_url",+ "image_url": {"url": attachment.url},+ }+ )+ else:+ raise ValueError(+ f"Unsupported content type {content_type}"+ )++ chat_messages.append({"role": message.role, "content": parts})++ response = client.chat_completion(+ chat_messages,+ max_tokens=max_tokens.value,+ temperature=temperature.value,+ top_p=top_p.value,+ stream=False,+ )++ # You can return strings, markdown, charts, tables, dataframes, and more.+ return response.choices[0].message.content+ return max_tokens, respond, system_message, temperature, top_p+++def __():+ # If you need to do anything _reactively_ to the chat messages,+ # you can access the chat messages using the `chat.value` attribute.+ # chat.value+ return+++if __name__ == "__main__":+ app.run()diff --git a/examples/third_party/huggingface/text-to-image.py b/examples/third_party/huggingface/text-to-image.pynew file mode 100644index 0000000000..4258e5d874--- /dev/null+++ b/examples/third_party/huggingface/text-to-image.py@@ -0,0 +1,266 @@+# /// script+# requires-python = ">=3.12"+# dependencies = [+# "accelerate==1.1.0",+# "diffusers==0.31.0",+# "marimo",+# "numpy==2.1.3",+# "torch==2.5.1",+# "tqdm==4.66.6",+# "transformers==4.46.1",+# ]+# ///++import marimo++__generated_with = "0.9.14"+app = marimo.App(width="medium")++[email protected](hide_code=True)+def __():+ import marimo as mo+ import numpy as np+ import random+ import transformers++ import tqdm++ # Patch tqdm to work marimo notebooks+ tqdm.auto.tqdm = tqdm.notebook.tqdm++ from diffusers import DiffusionPipeline+ import torch++ MAX_SEED = np.iinfo(np.int32).max+ MAX_IMAGE_SIZE = 1024++ model_repo_id = (+ "stabilityai/sdxl-turbo" # Replace to the model you would like to use+ )+ return (+ DiffusionPipeline,+ MAX_IMAGE_SIZE,+ MAX_SEED,+ mo,+ model_repo_id,+ np,+ random,+ torch,+ tqdm,+ transformers,+ )+++def __(mo, model_repo_id):+ mo.md(f"""# HuggingFace Text-to-Image: **{model_repo_id}**""")+ return++[email protected](hide_code=True)+def __():+ examples = [+ "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",+ "An astronaut riding a green horse",+ "A delicious ceviche cheesecake slice",+ ]+ return (examples,)+++def __(+ DiffusionPipeline,+ MAX_SEED,+ mo,+ model_repo_id,+ random,+ torch,+):+ device = "cuda" if torch.cuda.is_available() else "cpu"++ if torch.cuda.is_available():+ torch_dtype = torch.float16+ else:+ torch_dtype = torch.float32++ pipe = DiffusionPipeline.from_pretrained(+ model_repo_id, torch_dtype=torch_dtype+ )+ pipe = pipe.to(device)+++ def infer(+ prompt,+ negative_prompt,+ seed,+ randomize_seed,+ width,+ height,+ guidance_scale,+ num_inference_steps,+ ):+ if randomize_seed:+ seed = random.randint(0, MAX_SEED)++ generator = torch.Generator().manual_seed(seed)++ image = pipe(+ prompt=prompt,+ negative_prompt=negative_prompt,+ guidance_scale=guidance_scale,+ num_inference_steps=num_inference_steps,+ width=width,+ height=height,+ generator=generator,+ ).images[0]++ return image, seed+++ mo.output.clear() # Clear loading tdqm+ return device, infer, pipe, torch_dtype+++def __(mo):+ get_prompt, set_prompt = mo.state("")+ return get_prompt, set_prompt+++def __(get_prompt, mo, set_prompt):+ prompt = mo.ui.text_area(+ placeholder="Enter your prompt",+ label="Prompt",+ full_width=True,+ value=get_prompt(),+ on_change=set_prompt,+ )+ return (prompt,)+++def __(examples, mo, set_prompt):+ def _on_click(example):+ def handle(v):+ set_prompt(example)++ return handle+++ buttons = mo.ui.array(+ [+ mo.ui.button(label=example, on_click=_on_click(example))+ for example in examples+ ]+ )++ example_options = mo.vstack(buttons)+ return buttons, example_options+++def __(MAX_IMAGE_SIZE, MAX_SEED, example_options, mo, prompt):+ run_button = mo.ui.run_button(label="Run", kind="success", full_width=True)++ negative_prompt = mo.ui.text_area(+ placeholder="Enter a negative prompt", label="Negative prompt"+ )++ seed = mo.ui.slider(start=0, stop=MAX_SEED, value=0, label="Seed")++ randomize_seed = mo.ui.checkbox(label="Randomize seed", value=True)++ width = mo.ui.slider(+ start=256, stop=MAX_IMAGE_SIZE, step=32, value=1024, label="Width"+ )+ height = mo.ui.slider(+ start=256, stop=MAX_IMAGE_SIZE, step=32, value=1024, label="Height"+ )++ guidance_scale = mo.ui.slider(+ start=0.0, stop=10.0, step=0.1, value=0.0, label="Guidance scale"+ )++ num_inference_steps = mo.ui.slider(+ start=1, stop=50, step=1, value=2, label="Number of inference steps"+ )++ # Create advanced settings in an accordion+ advanced_settings = mo.accordion(+ {+ "::lucide:list:: Examples": example_options,+ "::lucide:settings:: Advanced Settings": mo.hstack(+ [+ mo.vstack([negative_prompt, seed, randomize_seed]),+ mo.vstack(+ [width, height, guidance_scale, num_inference_steps],+ align="end",+ ),+ ]+ ).style(padding="10px"),+ },+ )++ # Layout the main interface+ mo.vstack([prompt, run_button, advanced_settings])+ return (+ advanced_settings,+ guidance_scale,+ height,+ negative_prompt,+ num_inference_steps,+ randomize_seed,+ run_button,+ seed,+ width,+ )+++def __(mo):+ get_image, set_image = mo.state(None)+ return get_image, set_image+++def __(+ guidance_scale,+ height,+ infer,+ mo,+ negative_prompt,+ num_inference_steps,+ prompt,+ randomize_seed,+ run_button,+ seed,+ set_image,+ width,+):+ mo.stop(not run_button.value)++ _image, _seed = infer(+ prompt.value,+ negative_prompt.value,+ seed.value,+ randomize_seed.value,+ width.value,+ height.value,+ guidance_scale.value,+ num_inference_steps.value,+ )+ set_image(_image)+ mo.output.clear() # Clear loading tdqm+ return+++def __(get_image):+ get_image()+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_output/formatters/tqdm_formatters.py b/marimo/_output/formatters/tqdm_formatters.pyindex 4ca3e750a5..50e56d743b 100644--- a/marimo/_output/formatters/tqdm_formatters.py+++ b/marimo/_output/formatters/tqdm_formatters.py@@ -35,7 +35,9 @@ class TqdmFormatter(FormatterFactory):total = args[2]return progress_bar(- collection=iterable, title=desc, total=total+ collection=iterable,+ title=desc or "Loading...",+ total=total,)tqdm.notebook.tqdm = tqdm_to_progress_bar