Spaces:
Sleeping
Sleeping
add examples
Browse filesFiles changed (5)
- Dockerfile+3
- app.pyDeleted-470
- examples/chatbot.pyAdded+152
- examples/dataset_explorer.pyAdded+108
- requirements.txt+3
29 unmodified lines30313233343529 unmodified lines# Set working directoryWORKDIR /data# Set userUSER user29 unmodified lines30313233343536373829 unmodified lines# Set working directoryWORKDIR /data# Copy examplesCOPY --chown=user:user ./examples ./examples# Set userUSER user
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470import marimo
__generated_with = "0.9.2"app = marimo.App()
@app.celldef __(): import marimo as mo
mo.md("# Welcome to marimo! 🌊🍃") return (mo,)
@app.celldef __(mo): slider = mo.ui.slider(1, 22) return (slider,)
@app.celldef __(mo, slider): mo.md( f""" marimo is a **reactive** Python notebook.
This means that unlike traditional notebooks, marimo notebooks **run automatically** when you modify them or interact with UI elements, like this slider: {slider}.
{"##" + "🍃" * slider.value} """ ) return
@app.cell(hide_code=True)def __(mo): mo.accordion( { "Tip: disabling automatic execution": mo.md( rf""" marimo lets you disable automatic execution: just go into the notebook settings and set
"Runtime > On Cell Change" to "lazy".
When the runtime is lazy, after running a cell, marimo marks its descendants as stale instead of automatically running them. The lazy runtime puts you in control over when cells are run, while still giving guarantees about the notebook state. """ ) } ) return
@app.cell(hide_code=True)def __(mo): mo.md( """ Tip: This is a tutorial notebook. You can create your own notebooks by entering `marimo edit` at the command line. """ ).callout() return
@app.cell(hide_code=True)def __(mo): mo.md( """ ## 1. Reactive execution
A marimo notebook is made up of small blocks of Python code called cells.
marimo reads your cells and models the dependencies among them: whenever a cell that defines a global variable is run, marimo **automatically runs** all cells that reference that variable.
Reactivity keeps your program state and outputs in sync with your code, making for a dynamic programming environment that prevents bugs before they happen. """ ) return
@app.cell(hide_code=True)def __(changed, mo): ( mo.md( f""" **✨ Nice!** The value of `changed` is now {changed}.
When you updated the value of the variable `changed`, marimo **reacted** by running this cell automatically, because this cell references the global variable `changed`.
Reactivity ensures that your notebook state is always consistent, which is crucial for doing good science; it's also what enables marimo notebooks to double as tools and apps. """ ) if changed else mo.md( """ **🌊 See it in action.** In the next cell, change the value of the variable `changed` to `True`, then click the run button. """ ) ) return
@app.celldef __(): changed = False return (changed,)
@app.cell(hide_code=True)def __(mo): mo.accordion( { "Tip: execution order": ( """ The order of cells on the page has no bearing on the order in which cells are executed: marimo knows that a cell reading a variable must run after the cell that defines it. This frees you to organize your code in the way that makes the most sense for you. """ ) } ) return
@app.cell(hide_code=True)def __(mo): mo.md( """ **Global names must be unique.** To enable reactivity, marimo imposes a constraint on how names appear in cells: no two cells may define the same variable. """ ) return
@app.cell(hide_code=True)def __(mo): mo.accordion( { "Tip: encapsulation": ( """ By encapsulating logic in functions, classes, or Python modules, you can minimize the number of global variables in your notebook. """ ) } ) return
@app.cell(hide_code=True)def __(mo): mo.accordion( { "Tip: private variables": ( """ Variables prefixed with an underscore are "private" to a cell, so they can be defined by multiple cells. """ ) } ) return
@app.cell(hide_code=True)def __(mo): mo.md( """ ## 2. UI elements
Cells can output interactive UI elements. Interacting with a UI element **automatically triggers notebook execution**: when you interact with a UI element, its value is sent back to Python, and every cell that references that element is re-run.
marimo provides a library of UI elements to choose from under `marimo.ui`. """ ) return
@app.celldef __(mo): mo.md("""**🌊 Some UI elements.** Try interacting with the below elements.""") return
@app.celldef __(mo): icon = mo.ui.dropdown(["🍃", "🌊", "✨"], value="🍃") return (icon,)
@app.celldef __(icon, mo): repetitions = mo.ui.slider(1, 16, label=f"number of {icon.value}: ") return (repetitions,)
@app.celldef __(icon, repetitions): icon, repetitions return
@app.celldef __(icon, mo, repetitions): mo.md("# " + icon.value * repetitions.value) return
@app.cell(hide_code=True)def __(mo): mo.md( """ ## 3. marimo is just Python
marimo cells parse Python (and only Python), and marimo notebooks are stored as pure Python files — outputs are _not_ included. There's no magical syntax.
The Python files generated by marimo are:
- easily versioned with git, yielding minimal diffs - legible for both humans and machines - formattable using your tool of choice, - usable as Python scripts, with UI elements taking their default values, and - importable by other modules (more on that in the future). """ ) return
@app.cell(hide_code=True)def __(mo): mo.md( """ ## 4. Running notebooks as apps
marimo notebooks can double as apps. Click the app window icon in the bottom-right to see this notebook in "app view."
Serve a notebook as an app with `marimo run` at the command-line. Of course, you can use marimo just to level-up your notebooking, without ever making apps. """ ) return
@app.cell(hide_code=True)def __(mo): mo.md( """ ## 5. The `marimo` command-line tool
**Creating and editing notebooks.** Use
``` marimo edit ```
in a terminal to start the marimo notebook server. From here you can create a new notebook or edit existing ones.
**Running as apps.** Use
``` marimo run notebook.py ```
to start a webserver that serves your notebook as an app in read-only mode, with code cells hidden.
**Convert a Jupyter notebook.** Convert a Jupyter notebook to a marimo notebook using `marimo convert`:
``` marimo convert your_notebook.ipynb > your_app.py ```
**Tutorials.** marimo comes packaged with tutorials:
- `dataflow`: more on marimo's automatic execution - `ui`: how to use UI elements - `markdown`: how to write markdown, with interpolated values and LaTeX - `plots`: how plotting works in marimo - `sql`: how to use SQL - `layout`: layout elements in marimo - `fileformat`: how marimo's file format works - `markdown-format`: for using `.md` files in marimo - `for-jupyter-users`: if you are coming from Jupyter
Start a tutorial with `marimo tutorial`; for example,
``` marimo tutorial dataflow ```
In addition to tutorials, we have examples in our [our GitHub repo](https://www.github.com/marimo-team/marimo/tree/main/examples). """ ) return
@app.cell(hide_code=True)def __(mo): mo.md( """ ## 6. The marimo editor
Here are some tips to help you get started with the marimo editor. """ ) return
@app.celldef __(mo, tips): mo.accordion(tips) return
@app.cell(hide_code=True)def __(mo): mo.md("""## Finally, a fun fact""") return
@app.cell(hide_code=True)def __(mo): mo.md( """ The name "marimo" is a reference to a type of algae that, under the right conditions, clumps together to form a small sphere called a "marimo moss ball". Made of just strands of algae, these beloved assemblages are greater than the sum of their parts. """ ) return
@app.cell(hide_code=True)def __(): tips = { "Saving": ( """ **Saving**
- _Name_ your app using the box at the top of the screen, or with `Ctrl/Cmd+s`. You can also create a named app at the command line, e.g., `marimo edit app_name.py`.
- _Save_ by clicking the save icon on the bottom right, or by inputting `Ctrl/Cmd+s`. By default marimo is configured to autosave. """ ), "Running": ( """ 1. _Run a cell_ by clicking the play ( ▷ ) button on the top right of a cell, or by inputting `Ctrl/Cmd+Enter`.
2. _Run a stale cell_ by clicking the yellow run button on the right of the cell, or by inputting `Ctrl/Cmd+Enter`. A cell is stale when its code has been modified but not run.
3. _Run all stale cells_ by clicking the play ( ▷ ) button on the bottom right of the screen, or input `Ctrl/Cmd+Shift+r`. """ ), "Console Output": ( """ Console output (e.g., `print()` statements) is shown below a cell. """ ), "Creating, Moving, and Deleting Cells": ( """ 1. _Create_ a new cell above or below a given one by clicking the plus button to the left of the cell, which appears on mouse hover.
2. _Move_ a cell up or down by dragging on the handle to the right of the cell, which appears on mouse hover.
3. _Delete_ a cell by clicking the trash bin icon. Bring it back by clicking the undo button on the bottom right of the screen, or with `Ctrl/Cmd+Shift+z`. """ ), "Disabling Automatic Execution": ( """ Via the notebook settings (gear icon) or footer panel, you can disable automatic execution. This is helpful when working with expensive notebooks or notebooks that have side-effects like database transactions. """ ), "Disabling Cells": ( """ You can disable a cell via the cell context menu. marimo will never run a disabled cell or any cells that depend on it. This can help prevent accidental execution of expensive computations when editing a notebook. """ ), "Code Folding": ( """ You can collapse or fold the code in a cell by clicking the arrow icons in the line number column to the left, or by using keyboard shortcuts.
Use the command palette (`Ctrl/Cmd+k`) or a keyboard shortcut to quickly fold or unfold all cells. """ ), "Code Formatting": ( """ If you have [ruff](https://github.com/astral-sh/ruff) installed, you can format a cell with the keyboard shortcut `Ctrl/Cmd+b`. """ ), "Command Palette": ( """ Use `Ctrl/Cmd+k` to open the command palette. """ ), "Keyboard Shortcuts": ( """ Open the notebook menu (top-right) or input `Ctrl/Cmd+Shift+h` to view a list of all keyboard shortcuts. """ ), "Configuration": ( """ Configure the editor by clicking the gears icon near the top-right of the screen. """ ), } return (tips,)
if __name__ == "__main__": app.run()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152import marimo
__generated_with = "0.9.14"app = marimo.App(width="medium")
@app.celldef __(): import marimo as mo import os from huggingface_hub import InferenceClient return InferenceClient, mo, os
@app.celldef __(): MODEL_NAME = "HuggingFaceH4/zephyr-7b-beta" return (MODEL_NAME,)
@app.cell(hide_code=True)def __(MODEL_NAME, mo): mo.md(f""" # Chat with **{MODEL_NAME}** """) return
@app.celldef __(max_tokens, mo, system_message, temperature, top_p): mo.hstack( [ system_message, mo.vstack([temperature, top_p, max_tokens], align="end"), ], ) return
@app.celldef __(mo, respond): chat = mo.ui.chat( model=respond, prompts=["Tell me a joke.", "What is the square root of {{number}}?"], ) chat return (chat,)
@app.celldef __(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
@app.celldef __(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
@app.celldef __(): # 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108import marimo
__generated_with = "0.9.18"app = marimo.App(width="full")
@app.celldef __(): datasets = [ # Add your own HF datasets "scikit-learn/iris/Iris.csv", "scikit-learn/adult-census-income/adult.csv", "scikit-learn/auto-mpg/auto-mpg.csv", "scikit-learn/credit-card-clients/UCI_Credit_Card.csv", "scikit-learn/Fish/Fish.csv", "scikit-learn/tips/tips.csv", ] return (datasets,)
@app.cell(hide_code=True)def __(mo): mo.md(r"""## Select a dataset""") return
@app.cell(hide_code=True)def __(datasets, mo): dataset = mo.ui.dropdown(datasets, value=datasets[0], label="Select a dataset") no_limit = mo.ui.switch(label="Limit 1000", value=True) mo.hstack([dataset, no_limit]) return dataset, no_limit
@app.celldef __(dataset, mo, no_limit): explore = mo.sql( f""" CREATE OR REPLACE TEMP TABLE explore AS (FROM 'hf://datasets/{dataset.value}') {'LIMIT 1000' if no_limit.value else ''};
FROM explore; """ ) return (explore,)
@app.cell(hide_code=True)def __(mo): mo.md(r"""## Summary""") return
@app.cell(hide_code=True)def __(explore, mo): _schema = mo.accordion({"Schema": explore.schema})
mo.md(f""" * Total rows: **{len(explore):,}** * Total columns: **{len(explore.columns)}**
{_schema} """) return
@app.celldef __(explore): explore.describe() return
@app.cell(hide_code=True)def __(mo): mo.md("""## Manipulate the data""") return
@app.celldef __(explore, mo): transformed = mo.ui.dataframe(explore) transformed return (transformed,)
@app.cell(hide_code=True)def __(mo): mo.md(r"""## Explore the data""") return
@app.celldef __(mo, transformed): mo.ui.data_explorer(transformed.value) return
@app.cell(hide_code=True)def __(): # Imports import marimo as mo import polars return mo, polars
if __name__ == "__main__": app.run()123456marimo[sql]polarsaltair# Or a specific version# marimo>=0.9.0123456789huggingface-hub==0.26.2marimo[sql]polarsaltairopenaipyarrow# Or a specific version# marimo>=0.9.0
Dockerfile+3
app.pyDeleted-470
examples/chatbot.pyAdded+152
examples/dataset_explorer.pyAdded+108
requirements.txt+3