From c92e166f551909a6b57fd6c1a663b7b43db09a95 Mon Sep 17 00:00:00 2001 From: 22crodriguez <22crodriguez@ibadia.cat> Date: Wed, 4 Nov 2026 22:29:32 +0100 Subject: [PATCH] Add an opt-in scene-based video production pipeline\n\nIntroduce versioned scene plans, media manifests, quality reports, and timelines to plan narration, search stock footage, validate visual matches with TwelveLabs, and synchronize selected media with subtitles or TTS cues. Preserve the legacy workflow as the default and configure whether scene failures fall back or stop task generation.\n\nExtend video rendering with configurable export profiles, render metrics, subtitle style presets, optional scene labels, and audio mixing controls for ducking, normalization, peak protection, fades, and local sound effects. Add WebUI controls, English and Chinese translations, example configuration, and scene pipeline documentation.\n\nAdd comprehensive service and integration coverage for scene planning, media selection, timeline rendering, audio, exports, task artifacts, API settings, and WebUI behavior. Include a Streamlit development skill with reference guides, app templates, and theme configurations. --- .../skills/developing-with-streamlit/SKILL.md | 260 +++++ .../assets/templates/apps/README.md | 183 ++++ .../apps/dashboard-companies/pyproject.toml | 11 + .../apps/dashboard-companies/streamlit_app.py | 429 ++++++++ .../apps/dashboard-compute/pyproject.toml | 11 + .../apps/dashboard-compute/streamlit_app.py | 459 +++++++++ .../dashboard-feature-usage/pyproject.toml | 11 + .../dashboard-feature-usage/streamlit_app.py | 370 +++++++ .../apps/dashboard-metrics/pyproject.toml | 11 + .../apps/dashboard-metrics/streamlit_app.py | 489 +++++++++ .../dashboard-seattle-weather/pyproject.toml | 11 + .../streamlit_app.py | 274 +++++ .../apps/dashboard-stock-peers/pyproject.toml | 11 + .../dashboard-stock-peers/streamlit_app.py | 346 +++++++ .../assets/templates/themes/README.md | 50 + .../themes/configs/dense-dashboard.toml | 125 +++ .../templates/themes/configs/dracula.toml | 39 + .../themes/configs/financial-dashboard.toml | 77 ++ .../templates/themes/configs/fluent.toml | 49 + .../templates/themes/configs/jupyter.toml | 49 + .../templates/themes/configs/material-ui.toml | 45 + .../templates/themes/configs/minimal.toml | 39 + .../assets/templates/themes/configs/nord.toml | 39 + .../themes/configs/one-dark-pro.toml | 41 + .../templates/themes/configs/shadcn-dual.toml | 79 ++ .../templates/themes/configs/shadcn.toml | 49 + .../themes/configs/solarized-light.toml | 39 + .../templates/themes/configs/ubuntu.toml | 50 + .../templates/themes/configs/vscode.toml | 40 + .../references/api-reference.md | 194 ++++ .../references/authentication.md | 159 +++ .../references/best-practices.md | 416 ++++++++ .../references/ccv2-packaged-components.md | 230 +++++ .../references/ccv2-state-sync.md | 150 +++ .../references/ccv2-theme-css-variables.md | 252 +++++ .../references/ccv2-troubleshooting.md | 153 +++ .../references/chat-ui.md | 254 +++++ .../references/cli.md | 190 ++++ .../references/code-organization.md | 74 ++ .../references/custom-components-v2.md | 231 +++++ .../references/dashboards.md | 192 ++++ .../references/data-display.md | 427 ++++++++ .../references/design.md | 211 ++++ .../references/environment-setup.md | 123 +++ .../references/layouts.md | 337 +++++++ .../references/markdown.md | 296 ++++++ .../references/media-display.md | 74 ++ .../references/multipage-apps.md | 218 ++++ .../references/performance.md | 490 +++++++++ .../references/selection-widgets.md | 233 +++++ .../references/server-asgi.md | 461 +++++++++ .../references/session-state.md | 248 +++++ .../references/snowflake-connection.md | 207 ++++ .../references/testing.md | 251 +++++ .../references/text-display.md | 74 ++ .../references/theme.md | 550 +++++++++++ .../references/third-party-components.md | 156 +++ README-en.md | 3 + README.md | 2 + app/models/scene_media.py | 156 +++ app/models/scene_quality.py | 28 + app/models/scene_timeline.py | 76 ++ app/models/schema.py | 71 ++ app/models/video_plan.py | 118 +++ app/services/audio_mix.py | 112 +++ app/services/export_profiles.py | 50 + app/services/llm.py | 906 ++++++++++++++++- app/services/material.py | 30 + app/services/render_metrics.py | 86 ++ app/services/scene_media.py | 934 ++++++++++++++++++ app/services/scene_planner.py | 161 +++ app/services/scene_quality.py | 199 ++++ app/services/scene_timeline.py | 218 ++++ app/services/subtitle_presets.py | 109 ++ app/services/task.py | 342 ++++++- app/services/task_artifacts.py | 118 +++ app/services/twelvelabs.py | 106 +- app/services/video.py | 448 ++++++++- config.example.toml | 48 + docs/scene-pipeline.md | 143 +++ test/services/test_audio_mix.py | 58 ++ test/services/test_audio_schema.py | 40 + test/services/test_export_profiles.py | 44 + test/services/test_scene_media.py | 565 +++++++++++ test/services/test_scene_pipeline_e2e.py | 197 ++++ test/services/test_scene_planner.py | 84 ++ test/services/test_scene_quality.py | 78 ++ test/services/test_scene_timeline.py | 254 +++++ test/services/test_subtitle_presets.py | 54 + test/services/test_task.py | 190 ++++ test/services/test_task_artifacts.py | 67 ++ test/services/test_twelvelabs.py | 35 + test/services/test_video.py | 113 ++- test/services/test_video_plan.py | 104 ++ .../test_webui_generation_defaults.py | 22 + test/services/test_webui_i18n.py | 28 + webui/Main.py | 138 +++ webui/i18n/en.json | 28 + webui/i18n/zh.json | 28 + 99 files changed, 17026 insertions(+), 102 deletions(-) create mode 100644 .agents/skills/developing-with-streamlit/SKILL.md create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/apps/README.md create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-companies/pyproject.toml create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-companies/streamlit_app.py create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-compute/pyproject.toml create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-compute/streamlit_app.py create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-feature-usage/pyproject.toml create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-feature-usage/streamlit_app.py create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-metrics/pyproject.toml create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-metrics/streamlit_app.py create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-seattle-weather/pyproject.toml create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-seattle-weather/streamlit_app.py create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-stock-peers/pyproject.toml create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-stock-peers/streamlit_app.py create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/themes/README.md create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/themes/configs/dense-dashboard.toml create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/themes/configs/dracula.toml create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/themes/configs/financial-dashboard.toml create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/themes/configs/fluent.toml create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/themes/configs/jupyter.toml create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/themes/configs/material-ui.toml create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/themes/configs/minimal.toml create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/themes/configs/nord.toml create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/themes/configs/one-dark-pro.toml create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/themes/configs/shadcn-dual.toml create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/themes/configs/shadcn.toml create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/themes/configs/solarized-light.toml create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/themes/configs/ubuntu.toml create mode 100644 .agents/skills/developing-with-streamlit/assets/templates/themes/configs/vscode.toml create mode 100644 .agents/skills/developing-with-streamlit/references/api-reference.md create mode 100644 .agents/skills/developing-with-streamlit/references/authentication.md create mode 100644 .agents/skills/developing-with-streamlit/references/best-practices.md create mode 100644 .agents/skills/developing-with-streamlit/references/ccv2-packaged-components.md create mode 100644 .agents/skills/developing-with-streamlit/references/ccv2-state-sync.md create mode 100644 .agents/skills/developing-with-streamlit/references/ccv2-theme-css-variables.md create mode 100644 .agents/skills/developing-with-streamlit/references/ccv2-troubleshooting.md create mode 100644 .agents/skills/developing-with-streamlit/references/chat-ui.md create mode 100644 .agents/skills/developing-with-streamlit/references/cli.md create mode 100644 .agents/skills/developing-with-streamlit/references/code-organization.md create mode 100644 .agents/skills/developing-with-streamlit/references/custom-components-v2.md create mode 100644 .agents/skills/developing-with-streamlit/references/dashboards.md create mode 100644 .agents/skills/developing-with-streamlit/references/data-display.md create mode 100644 .agents/skills/developing-with-streamlit/references/design.md create mode 100644 .agents/skills/developing-with-streamlit/references/environment-setup.md create mode 100644 .agents/skills/developing-with-streamlit/references/layouts.md create mode 100644 .agents/skills/developing-with-streamlit/references/markdown.md create mode 100644 .agents/skills/developing-with-streamlit/references/media-display.md create mode 100644 .agents/skills/developing-with-streamlit/references/multipage-apps.md create mode 100644 .agents/skills/developing-with-streamlit/references/performance.md create mode 100644 .agents/skills/developing-with-streamlit/references/selection-widgets.md create mode 100644 .agents/skills/developing-with-streamlit/references/server-asgi.md create mode 100644 .agents/skills/developing-with-streamlit/references/session-state.md create mode 100644 .agents/skills/developing-with-streamlit/references/snowflake-connection.md create mode 100644 .agents/skills/developing-with-streamlit/references/testing.md create mode 100644 .agents/skills/developing-with-streamlit/references/text-display.md create mode 100644 .agents/skills/developing-with-streamlit/references/theme.md create mode 100644 .agents/skills/developing-with-streamlit/references/third-party-components.md create mode 100644 app/models/scene_media.py create mode 100644 app/models/scene_quality.py create mode 100644 app/models/scene_timeline.py create mode 100644 app/models/video_plan.py create mode 100644 app/services/audio_mix.py create mode 100644 app/services/export_profiles.py create mode 100644 app/services/render_metrics.py create mode 100644 app/services/scene_media.py create mode 100644 app/services/scene_planner.py create mode 100644 app/services/scene_quality.py create mode 100644 app/services/scene_timeline.py create mode 100644 app/services/subtitle_presets.py create mode 100644 docs/scene-pipeline.md create mode 100644 test/services/test_audio_mix.py create mode 100644 test/services/test_audio_schema.py create mode 100644 test/services/test_export_profiles.py create mode 100644 test/services/test_scene_media.py create mode 100644 test/services/test_scene_pipeline_e2e.py create mode 100644 test/services/test_scene_planner.py create mode 100644 test/services/test_scene_quality.py create mode 100644 test/services/test_scene_timeline.py create mode 100644 test/services/test_subtitle_presets.py create mode 100644 test/services/test_video_plan.py diff --git a/.agents/skills/developing-with-streamlit/SKILL.md b/.agents/skills/developing-with-streamlit/SKILL.md new file mode 100644 index 0000000000..2cceb8bf62 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/SKILL.md @@ -0,0 +1,260 @@ +--- +name: developing-with-streamlit +description: "**[REQUIRED]** Use for ALL Streamlit tasks: creating, editing, debugging, beautifying, styling, theming, or optimizing Streamlit applications. Also required for building custom components (inline or packaged), using st.components.v2, or any HTML/JS/CSS component work. Triggers: streamlit, st., dashboard, app.py, beautify, style, CSS, color, background, theme, button, widget styling, custom component, st.components, packaged component, pyproject.toml, asset_dir, CCv2, HTML/JS component." +--- + +# Developing with Streamlit + +This is a **routing skill** that directs you to specialized references for Streamlit development. + +## When to Use + +Invoke this skill when the user's request involves: +- Creating a new Streamlit app +- Editing or modifying an existing Streamlit app +- Debugging Streamlit issues (errors, session state bugs, performance problems) +- Beautifying or improving the visual design of a Streamlit app +- Optimizing Streamlit performance (caching, fragments, reruns) +- Building and running Streamlit apps +- Building chat, conversational, or agentic UIs (AI assistants, thinking expanders, chain-of-thought, tool-call timelines) +- Styling widgets (button colors, backgrounds, CSS customization) +- Advanced server configuration with `st.App`, ASGI, Starlette, FastAPI integration, custom routes, middleware, or lifespan hooks +- Any question about Streamlit widgets, layouts, or components + +**Trigger phrases:** "streamlit", "st.", "st.App", "dashboard", "app.py", "beautify app", "make it look better", "style", "CSS", "color", "background", "theme", "button", "slow rerun", "session state", "performance", "faster", "cache", "chat", "agentic", "chain of thought" + +## Best practices quick reference + +**IMPORTANT — `use_container_width` is deprecated.** Never add `use_container_width` to new code. Use `width="stretch"` or `width="content"` instead. Dataframes and most charts stretch to fill their container by default, but buttons, including `st.button`, `st.download_button`, `st.form_submit_button`, `st.link_button`, and `st.page_link`, default to `width="content"`; pass `width="stretch"` to make one fill its container. Remove `use_container_width` when you encounter it. + +Apply these defaults unless the user's app or request clearly needs a different approach. For examples, read `references/best-practices.md`. +- Do not use `use_container_width`; use `width="stretch"` or `width="content"` instead. +- Prefer native Streamlit elements over recreating UI with custom HTML. This includes UI created with `st.html`, `st.markdown(..., unsafe_allow_html=True)`, or deprecated `st.components.v1.html`. Use custom HTML only when no native element provides the required UI or behavior. +- Do not use the deprecated `st.components.v1.html` or `st.components.v1.iframe` commands. Use `st.iframe` for iframe-based rendering of URLs or HTML, and use `st.html` for HTML/CSS that should render directly in the app; `st.html` ignores JavaScript by default unless `unsafe_allow_javascript=True`. +- Do not apply CSS to style the app unless the user actively requests it. Use native Streamlit features and `.streamlit/config.toml` to customize the appearance; see the [theming reference](references/theme.md). +- Prefer Material Symbols icons (`:material/icon_name:`) over emojis for navigation, buttons, and labels. Use emojis sparingly, only when they add a special touch. +- Prefer sentence casing over title casing, including titles and widget labels. +- Do not use empty widget labels; use `label_visibility="collapsed"` or `label_visibility="hidden"` when a visible label is not desired. +- When an alert (`st.info`, `st.success`, `st.warning`, or `st.error`) needs a headline, pass keyword-only `title=` instead of bolding the first line of the body or adding a heading above it. +- Pass keyword-only `alt=` on images, charts, maps, media, iframes, PDFs, tables, dataframes, and data editors so assistive technologies can name them. Keep it short; decorative `alt=""` is only for `st.image` / `st.pyplot`. See `references/media-display.md` and `references/data-display.md`. +- Use `st.container(border=True)` for simple visual grouping. Prefer `st.container(horizontal=True)` over `st.columns` for responsive row layouts; use `st.columns` for fixed grids, precise width ratios, or side-by-side cards that must share a width. +- Align elements placed side by side: use `vertical_alignment="bottom"` for rows that mix labeled inputs with buttons, checkboxes, or toggles, and give sibling cards consistent content (for example, all metrics with or all without `delta`) or `height="stretch"`. See "Aligning elements side by side" in `references/layouts.md`. +- Prefer `st.navigation` and `st.Page` with an `app_pages/` folder over the legacy `pages/` directory, `st.page_link`, or other multipage-app v1 patterns. +- Always cache compute-intensive or expensive data-loading code. Use `st.cache_data` for serializable data and `st.cache_resource` for shared resources like API clients, raw connectors, and models; do not wrap `st.connection`, which is already cached. Include appropriate `ttl` and/or `max_entries` limits to prevent unbounded growth. Cache the expensive source data, then apply cheap interactive filters outside the cached function. +- Order scripts so fast UI (titles, layout, widgets) renders before slow computation. Streamlit streams elements top to bottom and temporarily greys out (marks stale) not-yet-redrawn elements from the previous run while a slow step is in progress, clearing each as the new run recreates it; put slow work last, reserve output slots with `st.container()`, or isolate slow sections in fragments. +- Use `st.fragment` for independent sections that should rerun separately from the rest of the app, such as auto-refreshing charts or controls that do not need to rerun the full page. +- Use `st.form` to batch related inputs and rerun only on submit, especially when intermediate widget changes would trigger expensive work. If some inputs must rerun to update others (for example, dependent options), use `on_change="ignore"` on the remaining inputs instead of a form (advanced; see "Skip reruns on individual widgets" in `references/performance.md`). +- Do not put expensive work unguarded inside `st.tabs`, `st.expander`, or `st.popover`: hidden, collapsed, or closed content still computes on every rerun, and caching doesn't change that. Pass `on_change="rerun"` and render each body only when the container's `.open` is `True`, or switch to `st.segmented_control` or `st.toggle` with an `if`. +- Use `st.secrets` for credentials. Never hard-code secrets in app code, never commit `.streamlit/secrets.toml`, and use parameterized queries for user-provided values. +- Prefer Vega-based charts (`st.altair_chart`, `st.line_chart`, `st.area_chart`, `st.scatter_chart`, `st.bar_chart`, `st.vega_lite_chart`) over `st.pyplot` and Plotly. Use `st.echarts_chart` when you already have an Apache ECharts option or a `pyecharts` chart. +- Prefer `st.segmented_control` over `st.radio(..., horizontal=True)`. +- For about 2–5 options, keep them visible instead of in a dropdown: `st.segmented_control` for a single choice and `st.pills(..., selection_mode="multi")` for several. Use `st.selectbox` or `st.multiselect` for longer lists. +- Use `st.menu_button` for a button that opens a short list of one-shot actions. Do not build one from `st.popover` with buttons or from `st.selectbox`. +- Initialize `st.session_state` in one clear place, avoid module-level mutable state for per-user data, and set widget `key` values when widgets repeat, parameters change dynamically, or code needs programmatic access. +- Keep page files as direct scripts; do not wrap page bodies in functions. Move shared business logic into modules. + +## Proactively Look Up API Details + +When selecting a Streamlit command, discovering functionality that may be newer than the agent's knowledge cutoff, validating available functionality, or using unfamiliar parameters, proactively look up the relevant local docs before coding: + +```bash +streamlit docs st. +``` + +Run this with the Streamlit installation relevant to the app being edited. Use `references/api-reference.md` to discover available public `st` commands and namespaces, then use `streamlit docs st.` for exact signatures, parameters, and docstrings. + +When annotating Streamlit-owned values returned by commands or stored in Session State, import the curated public types from `streamlit.typing` (also available as `st.typing`) instead of their internal implementation modules. See `references/api-reference.md` for the available types. + +## Workflow + +``` +Step 1: Locate the Streamlit source code + ↓ +Step 2: Identify task type and load appropriate reference(s) + ↓ +Step 3: Apply guidance from reference to edit code + ↓ +Step 4: Check if app is running and offer to run it +``` + +### Step 1: Locate the Streamlit Source Code (if needed) + +**Goal:** Identify the app file(s) to edit. **Skip this step if already clear from context.** + +**When to skip:** +- User mentioned a specific file path (e.g., "edit `src/app.py`") +- User has file(s) already in conversation context +- Working directory has an obvious single entry point (`app.py`, `streamlit_app.py`) + +**When to search:** +- User says "my streamlit app" without specifying which file +- Multiple Python files exist and it's unclear which is the entry point + +**If searching is needed:** + +1. **Quick scan** for Streamlit files: + ```bash + grep -rl 'import streamlit\|from streamlit' --include='*.py' . 2>/dev/null | head -10 + ``` + +2. **Apply entry point heuristics** (in priority order): + - `streamlit_app.py` at root → **this is the entry point** (canonical name) + - `app.py` at root → likely entry point + - File using `st.navigation` → entry point for multi-page apps + - Single `.py` file at root with streamlit import → entry point + - Files in `pages/` or `app_pages/` subdirectory → **NOT entry points** (these are sub-pages) + +3. **If entry point is obvious** → use it, no confirmation needed + + Example: Found `streamlit_app.py` and `pages/metrics.py` → use `streamlit_app.py` + +4. **Only ask if genuinely ambiguous** (e.g., multiple root-level candidates, none named `streamlit_app.py`): + ``` + Found multiple potential entry points: + - dashboard.py + - main.py + + Which is your main app? + ``` + +**Output:** Path to the main Streamlit source file(s) + +### Step 2: Identify Task Type and Route to Reference + +**Goal:** Determine what the user needs and load the appropriate guidance. + +### Reference routing table + +Use this routing table to select reference(s). **Always read the reference file** before making changes. + +> All file paths below are relative to this skill's directory (`streamlit/.agents/skills/developing-with-streamlit/`). + +| User Need | Reference to Read | +|-----------|-------------------| +| **General Streamlit best practices, app code review, or examples for recommended patterns and anti-patterns** — styling, layout, navigation, caching, fragments, forms, charts, widgets, accessible `alt=` names, session state, secrets, and page organization | read `references/best-practices.md` | +| **App is slow, reruns take too long, data loads repeatedly, or work is recomputed unnecessarily** — caching strategies (`st.cache_data`, `st.cache_resource`), `st.fragment` for partial reruns, (optionally) `parallel=True` when independent fragments can run concurrently, `on_change="ignore"` to update a widget without a rerun, and client-side validation and limits that catch bad input in the browser | read `references/performance.md` | +| **Building a dashboard with KPIs, metrics, and charts** — composing `st.metric`, charts, and data tables into clean dashboard layouts with columns and containers | read `references/dashboards.md` | +| **Making an app look polished** — brand colors, light/dark, page padding, icons (Material Symbols), spacing, visual hierarchy, and small design touches that elevate quality | read `references/theme.md` first, then `references/design.md` | +| **Choosing the right selection widget** — when to use `st.selectbox` vs `st.radio` vs `st.pills` vs `st.segmented_control` vs `st.multiselect` vs `st.feedback` (ratings), including modern replacements for deprecated patterns, and how to filter high-cardinality values (thousands+) without sending them all to the browser | read `references/selection-widgets.md` | +| **Custom themes, colors, padding, or styling requests** — configuring `.streamlit/config.toml` (including light/dark, sidebar, and `paddingTop`/`paddingBottom`), reading the active theme at runtime via `st.context.theme`, and the CSS pattern to use only when the user explicitly asks for CSS | read `references/theme.md` | +| **Page structure and layout** — `st.columns`, `st.tabs`, `st.sidebar`, `st.container`, `st.expander`, responsive layout patterns, when to use each container type, and aligning side-by-side elements (widget heights, `vertical_alignment`, equal-height cards) | read `references/layouts.md` | +| **Displaying or editing tabular data** — `st.dataframe` column configuration, `st.data_editor` for editable tables, `st.table` for small static tables and key-value/description lists, chart selection, accessible `alt=` names, and best practices for large datasets | read `references/data-display.md` | +| **Apache ECharts or pyecharts** — render an existing ECharts option dict, JSON string, or `pyecharts` chart with native `st.echarts_chart` rather than a third-party component (pass `alt=` carefully — it replaces the generated description) | read `references/data-display.md` | +| **Multi-page app architecture** — `st.navigation`, `st.Page`, page routing, shared state across pages, and structuring apps with multiple views | read `references/multipage-apps.md` | +| **Persisting values across reruns** — `st.session_state`, widget keys, callbacks (`on_change`, `on_click`), and patterns for stateful interactions | read `references/session-state.md` | +| **Making a selection shareable via URL / syncing a widget to a query param** — `bind="query-params"` + `key=` for automatic URL sync (don't hand-roll `st.query_params`) | read `references/session-state.md` | +| **Discovering available Streamlit public APIs, looking up `st.` commands, exact parameters, docstrings, signatures, public annotation types, or choosing the right top-level command** — quick table of public `st` commands, related public objects, and `streamlit.typing` exports plus CLI instructions for inspecting local docstrings | read `references/api-reference.md` | +| **Rich text formatting** — Markdown in `st.markdown` and widget labels, colored text (`:red[...]`), badges, Material Symbols icons (`:material/icon_name:`), LaTeX math, and Mermaid diagrams | read `references/markdown.md` | +| **Displaying text** — headings (`st.title`/`st.header`/`st.subheader`), `st.markdown`, `st.caption`, `st.code`, `st.text`, `st.badge`, and streaming text via `st.write_stream`; prefer explicit elements over `st.write`/magic | read `references/text-display.md` | +| **Displaying media** — images, video, audio, and PDFs (`st.image`, `st.video`, `st.audio`, `st.pdf`) via the native viewers instead of raw HTML embeds; keyword-only `alt=` for accessible names | read `references/media-display.md` | +| **Chat, conversational, and agentic UIs** — `st.chat_message`, `st.chat_input`, streaming responses with `st.write_stream`, compact thinking expanders with `type="compact"`, chain-of-thought / tool-call timelines with `type="step"` (including nesting steps inside a compact expander), and building AI assistant interfaces | read `references/chat-ui.md` | +| **Connecting to Snowflake** — `st.connection("snowflake")`, secrets configuration, querying data, and Snowflake-specific patterns | read `references/snowflake-connection.md` | +| **Building or packaging a custom component, triggering events back to Python from JS/HTML, custom HTML/JS with event handling (CCv2), OR any UI element that doesn't exist as a native Streamlit widget** (e.g., drag-and-drop, custom interactive visualization, canvas drawing) | read `references/custom-components-v2.md` — **IMPORTANT: Never use `st.components.v1` for new components; always use `st.components.v2.component()`.** (`st.components.v1.html` and `st.components.v1.iframe` are deprecated in favor of `st.iframe`.) | +| **Using third-party community components** — `streamlit-extras` (annotated text), `streamlit-pivot-table`, and other popular packages that extend Streamlit's built-in capabilities | read `references/third-party-components.md` | +| **Structuring app code** — when to split into modules vs keep in one file, helper functions, and clean project organization patterns | read `references/code-organization.md` | +| **Environment and dependency setup** — Python environment management, installing packages, and configuring the development environment for Streamlit apps | read `references/environment-setup.md` | +| **Streamlit CLI and configuration** — `streamlit run`, `streamlit config`, looking up docstrings (`streamlit docs `), `.streamlit/config.toml` (script-level and project-level), port settings, and server options | read `references/cli.md` | +| **Advanced server configuration** — `st.App`, ASGI entry points, custom HTTP routes, middleware, lifespan hooks, programmatic secrets, exception handlers, and FastAPI/Starlette mounting | read `references/server-asgi.md` | +| **Requiring users to sign in** — `st.login`/`st.logout`/`st.user` with OIDC, gating on `st.user.is_logged_in`, and `[auth]` secrets configuration (not a hand-rolled password gate) | read `references/authentication.md` | +| **Writing automated tests for an app** — `st.testing.v1.AppTest` for headless, in-process tests (simulate widgets, assert on elements) instead of launching a browser/server | read `references/testing.md` | + +**Fallback — "this widget doesn't exist in Streamlit":** + +If the user asks for a UI element or interaction that **has never been part of Streamlit's API** and cannot be built with any combination of native widgets (e.g., drag-and-drop, canvas drawing, custom interactive visualizations), **route to the CCv2 reference** (`references/custom-components-v2.md`). **Do not** route to CCv2 for UI that Streamlit already provides (e.g., `st.segmented_control`, `st.menu_button`, `st.echarts_chart`); check `references/api-reference.md` first. If the native command is newer than the app's installed Streamlit, suggest upgrading. + +**Common combinations:** + +For **beautifying/improving an app**, read in order: +1. `references/theme.md` — brand colors, light/dark, sidebar, padding (prefer config over CSS) +2. `references/design.md` — icons, hierarchy, micro-polish +3. `references/layouts.md` +4. `references/selection-widgets.md` + +Configure themes via `.streamlit/config.toml` (not CSS unless the user asks). Follow the decision table and key-placement rules in `references/theme.md`. + +For **building a dashboard**, read: +1. `references/dashboards.md` +2. `references/data-display.md` +3. `references/theme.md` — when the user wants a branded or polished look, pair with a theme (`theme.base` for a shared brand file/URL; `dense-dashboard` when the app should keep the appearance toggle and use compact padding) + +**IMPORTANT - Use templates:** + +When creating a **new dashboard app**, prefer starting from a template in `assets/templates/apps/`: +- If a template closely matches the request, copy it and adapt: + - `dashboard-metrics` — KPI cards with time-series charts + - `dashboard-companies` — company/entity comparison + - `dashboard-compute` — resource/credit monitoring + - `dashboard-feature-usage` — API endpoint usage analytics + - `dashboard-seattle-weather` — public dataset exploration + - `dashboard-stock-peers` — financial peer analysis +- If no template is a close match, start from scratch but borrow relevant patterns from the templates (e.g., caching with `@st.cache_data`, `filter_by_time_range()`, `st.set_page_config()`, chart utilities, layout structure) +- When the user wants a branded or polished look, pair the dashboard with a theme from `assets/templates/themes/configs/` (`dense-dashboard` only if the app should keep the appearance toggle and use compact padding), or point `theme.base` at an existing shared brand file or URL +- See `assets/templates/apps/README.md` for template descriptions + +When **editing an existing app**, use templates as reference for best practices: +- Check `assets/templates/apps/` for caching patterns, layout structure, and data-loading patterns +- Apply consistent patterns from templates to improve the existing code + +When applying a **custom theme**, use a config from `assets/templates/themes/configs/`: +- Prefer `theme.base` (shared corporate/brand TOML or URL) when several apps should inherit the same brand tokens, then override per app for layout-specific tweaks +- Choose **single-mode** (dracula, financial-dashboard, fluent, jupyter, material-ui, minimal, nord, one-dark-pro, shadcn, solarized-light, ubuntu, vscode) for a locked look +- Choose **dual-mode** (`shadcn-dual`, `dense-dashboard`) only when the settings appearance toggle should stay available +- Copy the chosen file to the app's `.streamlit/config.toml` (or point `theme.base` at a shared file) +- Themes include custom fonts via Google Fonts +- See `assets/templates/themes/README.md` for the theme list + +For **performance optimization**, read: +1. `references/performance.md` + +### Step 3: Apply Guidance to Edit Code + +**Goal:** Make changes to the Streamlit app following reference best practices. + +**Actions:** + +1. Apply the patterns and recommendations from the loaded reference(s) +2. Make edits to the source file(s) identified in Step 1 +3. Preserve existing functionality while adding improvements + +### Step 4: Check Running Apps and Offer to Run + +**Goal:** Help the user see their changes by checking if their app is running. + +**Actions:** + +1. **Check** for running Streamlit apps on ports 850*: + ```bash + lsof -nP -iTCP -sTCP:LISTEN 2>/dev/null | grep -i python | awk '{print $2, $9}' | grep ':85' || echo "No Streamlit apps detected on ports 850*" + ``` + +2. **Present** findings to user: + + **If app is running:** + ``` + Found Streamlit app running: + - PID: [pid] at http://localhost:[port] + + Your changes should be visible after a page refresh (Streamlit hot-reloads on file save). + ``` + + **If no app is running:** + ``` + No Streamlit app detected on ports 850*. + + Would you like me to run the app? I can start it with: + streamlit run [app_file.py] + ``` + +3. **If user wants to run the app**, start it: + ```bash + streamlit run [path/to/app.py] --server.port 8501 + ``` + +## Stopping Points + +- **Step 4**: Ask before starting the Streamlit app + +## Resources + +- [Streamlit API Reference](https://docs.streamlit.io/develop/api-reference) +- [Streamlit Gallery](https://streamlit.io/gallery) diff --git a/.agents/skills/developing-with-streamlit/assets/templates/apps/README.md b/.agents/skills/developing-with-streamlit/assets/templates/apps/README.md new file mode 100644 index 0000000000..05b1503d9e --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/apps/README.md @@ -0,0 +1,183 @@ +# Streamlit Dashboard App Templates + +This directory contains ready-to-use dashboard templates for Streamlit. Each template demonstrates best practices for building data-driven dashboards with modern UI patterns. + +## Available Templates + +### Public Demo Templates + +These templates are based on official Streamlit demo apps and work out of the box: + +| Template | Description | Key Features | +|----------|-------------|--------------| +| **dashboard-seattle-weather** | Weather data exploration dashboard | `st.metric`, `st.pills`, `st.altair_chart`, year comparison | +| **dashboard-stock-peers** | Stock peer analysis and comparison | `st.multiselect`, normalized charts, peer average calculation | + +### Analytics Dashboard Templates + +These templates demonstrate common dashboard patterns with synthetic data. Replace the data generation functions with your actual data sources: + +| Template | Description | Key Features | +|----------|-------------|--------------| +| **dashboard-metrics** | Core metrics dashboard with KPIs | `st.metric` KPI row with sparklines, `@st.fragment(parallel=True)` cards with `st.skeleton`, chart/table toggle, `st.popover` filters, TIME_RANGES (1M/6M/1Y/QTD/YTD/All) | +| **dashboard-feature-usage** | API endpoint usage analytics | Segmented control, starter kits, normalization toggle, rolling averages, conditional "Raw data" expander (`on_change="rerun"`) | +| **dashboard-companies** | Company leaderboard with drill-down | Interactive dataframe, sparkline columns, growth scores, custom cache spinner | +| **dashboard-compute** | Resource consumption monitoring | `@st.fragment(parallel=True)` with `st.skeleton`, `st.popover` filters, TIME_RANGES, line/bar toggle | + +## Quick Start + +### Run a Template Locally + +```bash +# Navigate to a template directory +cd assets/templates/apps/dashboard-metrics + +# Sync dependencies from pyproject.toml +uv sync + +# Run the app +uv run streamlit run streamlit_app.py +``` + +## Template Structure + +Each template follows this structure: + +``` +dashboard-{name}/ +├── streamlit_app.py # Main application code +└── pyproject.toml # Dependencies and metadata +``` + +## Canonical Patterns + +When creating new templates or adapting existing ones, follow these patterns for consistency. + +### Page Configuration + +Set page config near the top of the script, with `layout="wide"` and a Material icon: + +```python +st.set_page_config( + page_title="My Dashboard", + page_icon=":material/monitoring:", + layout="wide", +) +``` + +### Constants + +Use these standard constant names: + +```python +TIME_RANGES = ["1M", "6M", "1Y", "QTD", "YTD", "All"] +CHART_HEIGHT = 300 # Standard chart height in pixels +``` + +### Time Range Filtering + +All dashboard templates that support time filtering use the same `filter_by_time_range` function: + +```python +def filter_by_time_range(df: pd.DataFrame, x_col: str, time_range: str) -> pd.DataFrame: + """Filter dataframe by time range.""" + if time_range == "All" or df.empty: + return df + + df = df.copy() + df[x_col] = pd.to_datetime(df[x_col]) + max_date = df[x_col].max() + + if time_range == "1M": + min_date = max_date - timedelta(days=30) + elif time_range == "6M": + min_date = max_date - timedelta(days=180) + elif time_range == "1Y": + min_date = max_date - timedelta(days=365) + elif time_range == "QTD": + quarter_month = ((max_date.month - 1) // 3) * 3 + 1 + min_date = pd.Timestamp(date(max_date.year, quarter_month, 1)) + elif time_range == "YTD": + min_date = pd.Timestamp(date(max_date.year, 1, 1)) + else: + return df + + filtered: pd.DataFrame = df[df[x_col] >= min_date] + return filtered +``` + +### Popover Filters + +Compact filter controls using `st.popover`: + +```python +with st.popover("Filters", type="tertiary"): + line_options = st.pills("Lines", ["Daily", "7-day MA"], selection_mode="multi") + time_range = st.segmented_control("Time range", TIME_RANGES, default="All") +``` + +### Page Header with Reset Button + +```python +def render_page_header(title: str): + """Render page header with title and reset button.""" + with st.container( + horizontal=True, horizontal_alignment="distribute", vertical_alignment="center" + ): + st.markdown(title) + if st.button(":material/restart_alt: Reset", type="tertiary"): + st.session_state.clear() + st.rerun() +``` + +### Independent and parallel card updates with @st.fragment + +Wrap each card in `@st.fragment` so widget interactions rerun only that card, +not the whole page. If a dashboard has multiple cards with independent, +compute-intensive data loads, add `parallel=True` so those cards run +concurrently on a full app rerun. Wrap the loading body in `st.skeleton` so each +card shows a placeholder until its data is ready: + +```python +@st.fragment(parallel=True) +def metric_card(metric_name: str): + with st.container(border=True): + st.markdown(f"**{metric_name}**") # Stays stable while the body loads + with st.skeleton(height=300): + data = load_metric(metric_name) # Cached; loads in parallel + st.line_chart(data, alt=f"{metric_name} over time") +``` + +Keep `st.dialog` / `st.switch_page` and writes to containers created *outside* +the fragment out of parallel fragments — gate those behind a widget interaction +instead, where the fragment reruns sequentially. + +### Data Loading with Caching + +Cache the expensive load and bound it with a `ttl` (and/or `max_entries`) so the +cache stays fresh and doesn't grow without limit. Use a custom spinner message +for loaders that run directly in the page. Use `show_spinner=False` only when a +surrounding loading UI, such as `st.skeleton`, already provides feedback: + +```python +@st.cache_data(ttl="1h", show_spinner="Loading metric data...") +def load_metric_data() -> pd.DataFrame: + """Load metric data. Replace with your actual data source.""" + # Replace this with: + # - API call + # - Database query + # - Data warehouse query via st.connection + return generate_synthetic_data() +``` + +Guidelines: real-time data → `ttl="1m"`; metrics/reports → `ttl="5m"`–`"15m"`; +reference data → `ttl="1h"` or more; static data → no TTL. Use `max_entries` for +parameterized loaders so per-argument entries stay bounded. + +## Dependencies + +All templates require Python >=3.11 and use: +- `streamlit` +- `altair>=5.5.0` +- `pandas>=2.2.3` +- `numpy>=1.26.0` (most templates) diff --git a/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-companies/pyproject.toml b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-companies/pyproject.toml new file mode 100644 index 0000000000..07db294df8 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-companies/pyproject.toml @@ -0,0 +1,11 @@ +[project] +name = "dashboard-companies" +version = "1.0.0" +description = "A company analytics dashboard with leaderboard, filtering, and drill-down dialogs" +requires-python = ">=3.11" +dependencies = [ + "altair>=5.5.0", + "numpy>=1.26.0", + "pandas>=2.2.3", + "streamlit", +] diff --git a/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-companies/streamlit_app.py b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-companies/streamlit_app.py new file mode 100644 index 0000000000..49e375071c --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-companies/streamlit_app.py @@ -0,0 +1,429 @@ +# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Company analytics dashboard template. + +Demonstrates: +- Interactive dataframe with sparkline columns +- Segmented control for ranking (top spenders, gainers, shrinkers) +- Multi-select pills for account type filtering +- Time window filtering +- Growth score calculation +- Dialog popup for company details +- ``@st.cache_data(ttl=...)`` loader with a custom spinner message + +This template uses synthetic data. Replace ``generate_company_data()`` with +your actual data source (e.g., Snowflake queries, CRM APIs, etc.). +""" + +from datetime import date, timedelta + +import numpy as np +import pandas as pd + +import streamlit as st + +st.set_page_config( + page_title="Company Analytics", + page_icon=":material/business:", + layout="wide", +) + + +# ============================================================================= +# Synthetic Data Generation (Replace with your data source) +# ============================================================================= + +COMPANY_NAMES = [ + "Acme Corp", + "TechFlow Inc", + "DataDriven Co", + "CloudFirst Ltd", + "InnovateTech", + "ScaleUp Systems", + "PrimeData Inc", + "FutureStack", + "ByteWise Corp", + "StreamLine Co", + "Quantum Labs", + "NexGen Solutions", + "AlphaMetrics", + "BetaAnalytics", + "GammaInsights", + "DeltaData", + "OmegaTech", + "SigmaSoft", + "ThetaCloud", + "ZetaDigital", +] + +ACCOUNT_TYPES = ["Enterprise", "Growth", "Startup", "Trial", "Internal"] +REGIONS = ["North America", "EMEA", "APAC", "LATAM"] +SEGMENTS = ["Technology", "Finance", "Healthcare", "Retail", "Manufacturing"] + + +def generate_company_data(days: int = 90) -> pd.DataFrame: + """Generate synthetic company usage data. + + Replace this function with your actual data source. Caching happens in + ``load_company_data`` so the data is fetched once and reused across reruns. + """ + rng = np.random.default_rng(42) + + end_date = date.today() - timedelta(days=1) + start_date = end_date - timedelta(days=days) + dates = pd.date_range(start=start_date, end=end_date, freq="D") + + records = [] + + for company in COMPANY_NAMES: + # Assign static attributes + account_type = rng.choice(ACCOUNT_TYPES, p=[0.3, 0.25, 0.2, 0.15, 0.1]) + region = rng.choice(REGIONS) + segment = rng.choice(SEGMENTS) + + # Generate usage pattern + base_usage = rng.integers(100, 10000) + growth = rng.uniform(-0.005, 0.01) # Some companies shrink + + for i, dt in enumerate(dates): + # Base trend + trend = base_usage * (1 + growth) ** i + + # Weekly seasonality + if dt.dayofweek >= 5: + trend *= 0.3 + + # Random noise + daily_credits = max(0, trend * rng.uniform(0.7, 1.3)) + + records.append( + { + "company_name": company, + "date": dt, + "daily_credits": daily_credits, + "account_type": account_type, + "region": region, + "segment": segment, + } + ) + + return pd.DataFrame(records) + + +@st.cache_data(ttl="1h", show_spinner="Loading company data...") +def load_company_data() -> pd.DataFrame: + """Load all company data (cached). Replace with your data source.""" + return generate_company_data(days=90) + + +def _calc_growth(trend: list[float]) -> float: + """Return second-half vs first-half delta (rough trend indicator).""" + if not trend or len(trend) < 2: + return 0 + mid = len(trend) // 2 + first_half = sum(trend[:mid]) if mid > 0 else 0 + second_half = sum(trend[mid:]) + return second_half - first_half + + +def _to_list(val: object) -> list[object]: + """Wrap a scalar in a single-element list for MultiselectColumn display.""" + return [val] if pd.notna(val) else [] # type: ignore[call-overload] # ty: ignore[no-matching-overload] + + +def aggregate_companies( + df: pd.DataFrame, + days: int | None = None, + account_types: list[str] | None = None, + sort_by: str = "total_credits", +) -> pd.DataFrame: + """Filter and aggregate company data.""" + result = df.copy() + + # Filter by time window + if days: + cutoff = pd.Timestamp.now() - pd.Timedelta(days=days) + result = result[result["date"] >= cutoff] + + # Filter by account type + if account_types: + result = result[result["account_type"].isin(account_types)] + + if result.empty: + return pd.DataFrame() + + # Aggregate to company level + agg = ( + result.groupby("company_name") + .agg( + total_credits=("daily_credits", "sum"), + active_days=("date", "nunique"), + account_type=("account_type", "first"), + region=("region", "first"), + segment=("segment", "first"), + ) + .reset_index() + ) + + # Calculate daily average + agg["daily_avg"] = agg["total_credits"] / agg["active_days"] + + # Build sparkline data (list of daily values). + # `include_groups=False` silences a pandas 2.2+ FutureWarning about + # groupby keys being included in the applied function's input frame. + sparklines = ( + result.groupby("company_name") # ty: ignore[no-matching-overload] + .apply( + lambda x: x.sort_values("date")["daily_credits"].tolist(), + include_groups=False, # type: ignore[call-overload] + ) + .reset_index() + ) + sparklines.columns = ["company_name", "usage_trend"] + agg = agg.merge(sparklines, on="company_name") + + agg["growth_score"] = agg["usage_trend"].apply(_calc_growth) + + # Sort + if sort_by == "growth_asc": + agg = agg.sort_values("growth_score", ascending=True) + elif sort_by == "growth_desc": + agg = agg.sort_values("growth_score", ascending=False) + else: + agg = agg.sort_values("total_credits", ascending=False) + + return agg + + +def render_company_dialog( + company_name: str, company_row: pd.Series, df: pd.DataFrame +) -> None: + """Render company details inside a dialog.""" + company_data = df[df["company_name"] == company_name].sort_values("date") + + if company_data.empty: + st.warning("No data available for this company.") + return + + # Company info badges - extract from list format back to single value + account_type = ( + company_row["account_type"][0] if company_row["account_type"] else "Unknown" + ) + region = company_row["region"][0] if company_row["region"] else "Unknown" + segment = company_row["segment"][0] if company_row["segment"] else "Unknown" + total_credits = company_row["total_credits"] + + st.markdown( + f":blue-badge[{account_type}] " + f":violet-badge[{region}] " + f":orange-badge[{segment}] " + f":green-badge[{total_credits:,.0f} credits]" + ) + + # Summary metrics + col1, col2, col3 = st.columns(3) + with col1: + st.metric("Total Credits", f"{total_credits:,.0f}") + with col2: + st.metric("Active Days", f"{company_row['active_days']:,}") + with col3: + growth = company_row["growth_score"] + st.metric("Growth Score", f"{growth:+,.0f}") + + # Charts + col1, col2 = st.columns(2) + + with col1: + with st.container(border=True): + st.markdown("**Daily usage**") + st.line_chart( + company_data, + x="date", + y="daily_credits", + height=250, + alt="Daily credit usage over time", + ) + + with col2: + with st.container(border=True): + st.markdown("**Cumulative usage**") + chart_data = company_data.copy() + chart_data["cumulative"] = chart_data["daily_credits"].cumsum() + st.area_chart( + chart_data, + x="date", + y="cumulative", + height=250, + alt="Cumulative credit usage over time", + ) + + +# ============================================================================= +# Page Layout +# ============================================================================= + +st.markdown("# :material/business: Company Analytics") +st.caption("Track company adoption - usage, growth trends, and account details.") + +# Filters +with st.container(border=True): + st.markdown("**Filters**") + + # Company selection mode + sort_mode = st.segmented_control( + "Sort by", + options=[ + "All companies", + ":material/military_tech: Top spenders", + ":material/trending_down: Top shrinkers", + ":material/trending_up: Top gainers", + ], + default="All companies", + ) + + # Time window + timeframe_options = { + "All time": None, + "Last 28 days": 28, + "Last 7 days": 7, + } + timeframe = st.segmented_control( + "Time window", + options=list(timeframe_options.keys()), + default="Last 28 days", + ) + days_filter = timeframe_options.get(timeframe or "Last 28 days") + + # Account types + account_types = st.pills( + "Account types", + options=ACCOUNT_TYPES, + default=["Enterprise", "Growth", "Startup"], + selection_mode="multi", + ) + +# Determine sort order +if "Top shrinkers" in (sort_mode or ""): + sort_by = "growth_asc" +elif "Top gainers" in (sort_mode or ""): + sort_by = "growth_desc" +else: + sort_by = "total_credits" + +# Companies dataframe +with st.container(border=True): + # Guard against None: segmented_control returns None when deselected. + timeframe_text = ( + timeframe.lower() if timeframe and timeframe != "All time" else "all time" + ) + st.markdown(f"**Companies — {timeframe_text}**") + + all_data = load_company_data() + leaderboard = aggregate_companies( + all_data, + days=days_filter, + account_types=account_types, + sort_by=sort_by, + ) + + if leaderboard.empty: + st.warning("No company data found for the selected filters.") + st.stop() + + # Convert columns to lists for MultiselectColumn display (colored chips) + for col in ["account_type", "region", "segment"]: + leaderboard[col] = leaderboard[col].apply(_to_list) + + # Selection dataframe with cell-click support + selection = st.dataframe( + leaderboard, + column_config={ + "company_name": st.column_config.TextColumn( + "Company (click to view details)", + width="medium", + ), + "account_type": st.column_config.MultiselectColumn( + "Type", + options=ACCOUNT_TYPES, + color="auto", + width="small", + ), + "total_credits": st.column_config.NumberColumn( + "Credits", + format="%.0f", + ), + "growth_score": st.column_config.NumberColumn( + "Growth", + format="%+.0f", + help="Credit change: second half vs first half of period", + ), + "usage_trend": st.column_config.LineChartColumn( + "Trend", + width="medium", + ), + "daily_avg": st.column_config.NumberColumn( + "Daily Avg", + format="%.1f", + ), + "active_days": st.column_config.NumberColumn( + "Active Days", + format="%d", + ), + "region": st.column_config.MultiselectColumn( + "Region", + options=REGIONS, + color="auto", + ), + "segment": st.column_config.MultiselectColumn( + "Segment", + options=SEGMENTS, + color="auto", + ), + }, + column_order=[ + "company_name", + "account_type", + "total_credits", + "growth_score", + "usage_trend", + "daily_avg", + "region", + "segment", + ], + hide_index=True, + on_select="rerun", + selection_mode="single-cell", + key="company_leaderboard", + alt="Company usage leaderboard", + ) + +# Company drill-down via dialog when Company column cell is clicked +if selection.selection.cells: + cell = selection.selection.cells[0] # tuple: (row_index, column_name) + row_idx, col_name = cell + # Check if the clicked cell is in the company_name column + if col_name == "company_name": + selected_company = leaderboard.iloc[row_idx]["company_name"] + company_row = leaderboard.iloc[row_idx] + + @st.dialog(f"{selected_company}", width="large") + def show_company_dialog() -> None: + render_company_dialog( + selected_company, + company_row=company_row, + df=all_data, + ) + + show_company_dialog() diff --git a/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-compute/pyproject.toml b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-compute/pyproject.toml new file mode 100644 index 0000000000..9746d4fd84 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-compute/pyproject.toml @@ -0,0 +1,11 @@ +[project] +name = "dashboard-compute" +version = "1.0.0" +description = "A compute/resource consumption dashboard with multiple metric breakdowns" +requires-python = ">=3.11" +dependencies = [ + "altair>=5.5.0", + "numpy>=1.26.0", + "pandas>=2.2.3", + "streamlit", +] diff --git a/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-compute/streamlit_app.py b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-compute/streamlit_app.py new file mode 100644 index 0000000000..b54128b6b9 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-compute/streamlit_app.py @@ -0,0 +1,459 @@ +# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Compute/resource dashboard template. + +Demonstrates: +- Multiple metric cards in a grid layout +- ``@st.fragment(parallel=True)`` so cards load concurrently on full reruns and + rerun in isolation on widget interactions +- ``st.skeleton`` placeholders while each card's data loads +- ``@st.cache_data(ttl=...)`` loaders that keep data fresh and bounded +- Popover filters for each metric card +- Chart/table view toggle +- Time range filtering (1M, 6M, 1Y, QTD, YTD, All) +- Percentage normalization toggle +- Multiple breakdown dimensions + +This template uses synthetic data. Replace ``generate_*_data()`` with your +actual data source (e.g., Snowflake queries, cloud APIs, etc.). +""" + +import hashlib +from collections.abc import Callable +from datetime import date, timedelta + +import altair as alt +import numpy as np +import pandas as pd + +import streamlit as st + +st.set_page_config( + page_title="Compute Dashboard", + page_icon=":material/bolt:", + layout="wide", +) + + +# ============================================================================= +# Constants +# ============================================================================= + +TIME_RANGES = ["1M", "6M", "1Y", "QTD", "YTD", "All"] +ACCOUNT_TYPES = ["Paying", "Trial", "Internal"] +INSTANCE_TYPES = ["Standard", "High Memory", "High CPU", "GPU"] +REGIONS = ["us-west-2", "us-east-1", "eu-west-1", "ap-northeast-1"] +CHART_HEIGHT = 350 + + +# ============================================================================= +# Synthetic Data Generation +# ============================================================================= + + +def generate_time_series( + categories: list[str], + category_name: str, + start_date: date, + end_date: date, + base_values: dict[str, float] | None = None, +) -> pd.DataFrame: + """Generate synthetic time series data by category.""" + seed = int(hashlib.sha256(category_name.encode()).hexdigest(), 16) % 2**32 + rng = np.random.default_rng(seed) + + dates = pd.date_range(start=start_date, end=end_date, freq="D") + records = [] + + for category in categories: + base = ( + base_values.get(category, 1000) if base_values else rng.integers(500, 5000) + ) + growth = rng.uniform(0.001, 0.005) + + for i, dt in enumerate(dates): + trend = base * (1 + growth) ** i + if dt.dayofweek >= 5: + trend *= 0.4 + + daily = max(0, trend * rng.uniform(0.8, 1.2)) + + records.append( + { + "ds": dt, + category_name: category, + "daily_credits": daily, + } + ) + + df = pd.DataFrame(records) + + # Add 7-day moving average + df["credits_7d_ma"] = df.groupby(category_name)["daily_credits"].transform( + lambda x: x.rolling(7, min_periods=1).mean() + ) + + return df + + +@st.cache_data(ttl="1h", show_spinner=False) +def load_account_type_data() -> pd.DataFrame: + """Load credits by account type.""" + end_date = date.today() - timedelta(days=1) + start_date = end_date - timedelta(days=730) # 2 years + return generate_time_series( + ACCOUNT_TYPES, + "account_type", + start_date, + end_date, + base_values={"Paying": 8000, "Trial": 2000, "Internal": 1000}, + ) + + +@st.cache_data(ttl="1h", show_spinner=False) +def load_instance_type_data() -> pd.DataFrame: + """Load credits by instance type.""" + end_date = date.today() - timedelta(days=1) + start_date = end_date - timedelta(days=730) + return generate_time_series( + INSTANCE_TYPES, + "instance_type", + start_date, + end_date, + base_values={ + "Standard": 5000, + "High Memory": 3000, + "High CPU": 2000, + "GPU": 1500, + }, + ) + + +@st.cache_data(ttl="1h", show_spinner=False) +def load_region_data() -> pd.DataFrame: + """Load credits by region.""" + end_date = date.today() - timedelta(days=1) + start_date = end_date - timedelta(days=730) + return generate_time_series( + REGIONS, + "region", + start_date, + end_date, + base_values={ + "us-west-2": 4000, + "us-east-1": 3500, + "eu-west-1": 2500, + "ap-northeast-1": 1500, + }, + ) + + +# ============================================================================= +# Chart Utilities +# ============================================================================= + + +def filter_by_time_range(df: pd.DataFrame, x_col: str, time_range: str) -> pd.DataFrame: + """Filter dataframe by time range.""" + if time_range == "All" or df.empty: + return df + + df = df.copy() + df[x_col] = pd.to_datetime(df[x_col]) + max_date = df[x_col].max() + + if time_range == "1M": + min_date = max_date - timedelta(days=30) + elif time_range == "6M": + min_date = max_date - timedelta(days=180) + elif time_range == "1Y": + min_date = max_date - timedelta(days=365) + elif time_range == "QTD": + quarter_month = ((max_date.month - 1) // 3) * 3 + 1 + min_date = pd.Timestamp(date(max_date.year, quarter_month, 1)) + elif time_range == "YTD": + min_date = pd.Timestamp(date(max_date.year, 1, 1)) + else: + return df + + filtered: pd.DataFrame = df[df[x_col] >= min_date] + return filtered + + +def create_line_chart( + df: pd.DataFrame, + x_col: str, + y_col: str, + color_col: str, + height: int, + show_percent: bool = False, +) -> alt.Chart: + """Create a line chart.""" + y_format = ".1%" if show_percent else ",.0f" + + chart: alt.Chart = ( + alt.Chart(df) + .mark_line() + .encode( + x=alt.X(f"{x_col}:T", title=None), + y=alt.Y(f"{y_col}:Q", title="Credits", axis=alt.Axis(format=y_format)), + color=alt.Color(f"{color_col}:N", legend=alt.Legend(orient="bottom")), + tooltip=[ + alt.Tooltip(f"{x_col}:T", title="Date", format="%Y-%m-%d"), + alt.Tooltip( + f"{color_col}:N", title=color_col.replace("_", " ").title() + ), + alt.Tooltip(f"{y_col}:Q", title="Credits", format=y_format), + ], + ) + .properties(height=height) + .interactive() + ) + return chart + + +def create_bar_chart( + df: pd.DataFrame, + x_col: str, + y_col: str, + color_col: str, + height: int, + show_percent: bool = False, +) -> alt.Chart: + """Create a stacked bar chart.""" + y_format = ".1%" if show_percent else ",.0f" + + chart: alt.Chart = ( + alt.Chart(df) + .mark_bar() + .encode( + x=alt.X(f"{x_col}:T", title=None), + y=alt.Y( + f"{y_col}:Q", + title="Credits", + stack="normalize" if show_percent else True, + axis=alt.Axis(format=y_format), + ), + color=alt.Color(f"{color_col}:N", legend=alt.Legend(orient="bottom")), + tooltip=[ + alt.Tooltip(f"{x_col}:T", title="Date", format="%Y-%m-%d"), + alt.Tooltip(f"{color_col}:N"), + alt.Tooltip(f"{y_col}:Q", format=",.0f"), + ], + ) + .properties(height=height) + ) + return chart + + +# ============================================================================= +# Page Header Component +# ============================================================================= + + +def render_page_header(title: str) -> None: + """Render page header with title and reset button.""" + with st.container( + horizontal=True, horizontal_alignment="distribute", vertical_alignment="center" + ): + st.markdown(title) + if st.button(":material/restart_alt: Reset", type="tertiary"): + st.session_state.clear() + st.rerun() + + +# ============================================================================= +# Metric Card Component +# ============================================================================= + + +@st.fragment(parallel=True) +def dimension_metric( + *, + title: str, + loader: Callable[[], pd.DataFrame], + dim_col: str, + options: list[str], + options_label: str, + default_selection: list[str], + default_chart: str = "Line", + key_prefix: str, +) -> None: + """Metric card broken down by a single dimension, with independent state. + + The card is a parallel fragment: on a full app rerun each card loads its + own data concurrently in a thread pool, and clicking a popover filter only + reruns this card, not the whole page. Data is loaded inside ``st.skeleton`` + so the controls stay stable while the chart fills in. + + Parameters + ---------- + title : str + Card header text. + loader : Callable[[], pd.DataFrame] + Cached loader returning a frame with ``ds``, ``daily_credits``, + ``credits_7d_ma``, and ``dim_col``. Called inside the fragment so the + load runs concurrently with the other cards. + dim_col : str + Column name to split series on (e.g. ``"account_type"``). + options : list[str] + All possible values of ``dim_col``. + options_label : str + Label shown above the dimension selector pills. + default_selection : list[str] + Subset of ``options`` pre-selected when the card first renders. + default_chart : str + ``"Line"`` or ``"Bar"``. + key_prefix : str + Unique prefix used for every widget key inside the card. + """ + chart_default = ( + ":material/bar_chart: Bar" + if default_chart == "Bar" + else ":material/show_chart: Line" + ) + + with st.container(border=True): + with st.container( + horizontal=True, + horizontal_alignment="distribute", + vertical_alignment="center", + ): + st.markdown(f"**{title}**") + + view_mode = st.segmented_control( + "View", + options=[":material/show_chart:", ":material/table:"], + default=":material/show_chart:", + key=f"{key_prefix}_view", + label_visibility="collapsed", + ) + + with st.popover("Filters", type="tertiary"): + selected = st.pills( + options_label, + options=options, + default=default_selection, + selection_mode="multi", + key=f"{key_prefix}_select", + ) + line_options = st.pills( + "Lines", + options=["Daily", "7-day MA"], + default=["7-day MA"], + selection_mode="multi", + key=f"{key_prefix}_lines", + ) + chart_type = st.segmented_control( + "Chart type", + options=[":material/show_chart: Line", ":material/bar_chart: Bar"], + default=chart_default, + key=f"{key_prefix}_chart", + ) + show_percent = st.toggle( + "Show %", + value=False, + key=f"{key_prefix}_pct", + disabled="Line" in (chart_type or ""), + ) + time_range = st.segmented_control( + "Time range", + options=TIME_RANGES, + default="All", + key=f"{key_prefix}_time", + ) + + # Load this card's data and render inside a skeleton placeholder so each + # card fills in as soon as its own (cached) data is ready. + with st.skeleton(height=CHART_HEIGHT): + data = loader() + + selected = selected or default_selection + line_options = line_options or ["7-day MA"] + filtered = data[data[dim_col].isin(selected)] + filtered = filter_by_time_range(filtered, "ds", time_range or "All") + + y_col = "credits_7d_ma" if "7-day MA" in line_options else "daily_credits" + series = "7-day average" if "7-day MA" in line_options else "daily" + + if "table" in (view_mode or ""): + st.dataframe( + filtered, + height=CHART_HEIGHT, + hide_index=True, + alt=f"{title} data", + ) + elif "Bar" in (chart_type or ""): + st.altair_chart( + create_bar_chart( + filtered, "ds", y_col, dim_col, CHART_HEIGHT, show_percent + ), + alt=( + f"{title} {series} share by day" + if show_percent + else f"{title} {series} by day" + ), + ) + else: + st.altair_chart( + create_line_chart(filtered, "ds", y_col, dim_col, CHART_HEIGHT), + alt=f"{title} {series} over time", + ) + + +# ============================================================================= +# Page Layout +# ============================================================================= + +render_page_header("# :material/bolt: Compute Dashboard") + +# Row 1: Two metrics +col1, col2 = st.columns(2) + +with col1: + dimension_metric( + title="Credits by account type", + loader=load_account_type_data, + dim_col="account_type", + options=ACCOUNT_TYPES, + options_label="Account types", + default_selection=["Paying"], + default_chart="Line", + key_prefix="acct", + ) + +with col2: + dimension_metric( + title="Credits by instance type", + loader=load_instance_type_data, + dim_col="instance_type", + options=INSTANCE_TYPES, + options_label="Instance types", + default_selection=INSTANCE_TYPES, + default_chart="Line", + key_prefix="inst", + ) + +# Row 2: One metric (full width for region breakdown) +dimension_metric( + title="Credits by region", + loader=load_region_data, + dim_col="region", + options=REGIONS, + options_label="Regions", + default_selection=REGIONS, + default_chart="Bar", + key_prefix="region", +) diff --git a/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-feature-usage/pyproject.toml b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-feature-usage/pyproject.toml new file mode 100644 index 0000000000..59c631bdb1 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-feature-usage/pyproject.toml @@ -0,0 +1,11 @@ +[project] +name = "dashboard-feature-usage" +version = "1.0.0" +description = "A feature usage analytics dashboard with filtering and starter kits" +requires-python = ">=3.11" +dependencies = [ + "altair>=5.5.0", + "numpy>=1.26.0", + "pandas>=2.2.3", + "streamlit", +] diff --git a/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-feature-usage/streamlit_app.py b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-feature-usage/streamlit_app.py new file mode 100644 index 0000000000..19040b44ca --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-feature-usage/streamlit_app.py @@ -0,0 +1,370 @@ +# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""API usage dashboard template. + +Demonstrates: +- Segmented control for category selection +- Multiselect for endpoint filtering +- Starter kits / presets for quick selection +- Time series visualization with normalization +- Metric cards with 28-day deltas +- Rolling average options +- ``@st.cache_data(ttl=...)`` loader to keep data fresh and bounded +- Conditional rendering: the collapsed "Raw data" expander only computes and + sends its dataframe to the browser when it is open (``on_change="rerun"``) + +This template uses synthetic data. Replace ``generate_api_data()`` with your +actual data source (e.g., Snowflake queries, APIs, etc.). +""" + +from datetime import date, timedelta + +import altair as alt +import numpy as np +import pandas as pd + +import streamlit as st + +st.set_page_config( + page_title="API Usage Dashboard", + page_icon=":material/api:", + layout="wide", +) + + +# ============================================================================= +# Synthetic Data Generation (Replace with your data source) +# ============================================================================= + +# API categories and their endpoints +API_CATEGORIES = { + "Users": [ + "/users", + "/users/{id}", + "/users/me", + "/users/search", + "/users/bulk", + "/users/export", + ], + "Orders": [ + "/orders", + "/orders/{id}", + "/orders/create", + "/orders/cancel", + "/orders/refund", + "/orders/status", + ], + "Products": [ + "/products", + "/products/{id}", + "/products/search", + "/products/categories", + "/products/inventory", + ], + "Analytics": [ + "/analytics/events", + "/analytics/metrics", + "/analytics/reports", + "/analytics/dashboards", + ], +} + +# Starter kits - predefined endpoint selections +STARTER_KITS = { + "None": [], + "Core CRUD": ["/users", "/users/{id}", "/orders", "/orders/{id}"], + "Search": ["/users/search", "/products/search", "/products/categories"], + "Analytics": ["/analytics/events", "/analytics/metrics", "/analytics/reports"], + "High Volume": ["/users", "/products", "/orders", "/analytics/events"], +} + +ROLLING_OPTIONS = {"Raw": 1, "7-day average": 7, "28-day average": 28} + + +def generate_api_data( + endpoints: list[str], + start_date: date, + end_date: date, +) -> pd.DataFrame: + """Generate synthetic API usage data. + + Replace this function with your actual data source. + """ + rng = np.random.default_rng(42) + + dates = pd.date_range(start=start_date, end=end_date, freq="D") + records = [] + + for endpoint in endpoints: + # Each endpoint has different base traffic and growth + base = rng.integers(1000, 50000) + growth = rng.uniform(0.0005, 0.003) + + for i, dt in enumerate(dates): + # Base trend with growth + trend = base * (1 + growth) ** i + + # Weekly seasonality (lower on weekends) + if dt.dayofweek >= 5: + trend *= 0.4 + + # Random noise + value = trend * rng.uniform(0.85, 1.15) + + records.append( + { + "date": dt, + "endpoint": endpoint, + "request_count": int(value), + } + ) + + return pd.DataFrame(records) + + +@st.cache_data(ttl="1h", show_spinner="Loading API usage data...") +def load_api_data() -> pd.DataFrame: + """Load all API usage data (cached). Replace with your data source.""" + end_date = date.today() - timedelta(days=1) + start_date = end_date - timedelta(days=365) + + all_endpoints = [] + for endpoints in API_CATEGORIES.values(): + all_endpoints.extend(endpoints) + + return generate_api_data(all_endpoints, start_date, end_date) + + +def apply_rolling_average(df: pd.DataFrame, window: int) -> pd.DataFrame: + """Apply rolling average to request data.""" + if window == 1: + return df + + result = df.copy() + result["request_count"] = result.groupby("endpoint")["request_count"].transform( + lambda x: x.rolling(window, min_periods=1).mean() + ) + return result + + +def normalize_data(df: pd.DataFrame) -> pd.DataFrame: + """Normalize request counts to percentages (share of total per day).""" + result = df.copy() + daily_totals = result.groupby("date")["request_count"].transform("sum") + result["request_count"] /= daily_totals + return result + + +def calculate_delta(df: pd.DataFrame, endpoint: str) -> tuple[float, float | None]: + """Calculate 28-day delta for an endpoint.""" + endpoint_data = df[df["endpoint"] == endpoint].sort_values("date") + + if len(endpoint_data) < 2: + return endpoint_data["request_count"].iloc[-1], None + + latest = endpoint_data["request_count"].iloc[-1] + + if len(endpoint_data) > 28: + previous = endpoint_data["request_count"].iloc[-29] + else: + previous = endpoint_data["request_count"].iloc[0] + + delta = latest - previous + return latest, delta + + +# ============================================================================= +# Page Layout +# ============================================================================= + +# Load data +raw_data = load_api_data() + +# Header +st.markdown("# API Usage :material/api:") +st.caption("Select an API category to explore endpoint usage over time.") + +# Category selection (not centered) +category = st.segmented_control( + "Select category", + options=[ + ":material/person: Users", + ":material/shopping_cart: Orders", + ":material/inventory_2: Products", + ":material/analytics: Analytics", + ], + default=":material/person: Users", + label_visibility="collapsed", +) + +if not category: + st.warning("Please select a category above.", icon=":material/warning:") + st.stop() + +# Map display name to category key +category_map = { + ":material/person: Users": "Users", + ":material/shopping_cart: Orders": "Orders", + ":material/inventory_2: Products": "Products", + ":material/analytics: Analytics": "Analytics", +} +selected_category = category_map[category] + +st.subheader(f"{category} endpoints") + +# Layout: filters on left, chart on right +filter_col, chart_col = st.columns([1, 2]) + +with filter_col: + # Metric selection + with st.expander("Metric", expanded=True, icon=":material/analytics:"): + rolling_label = st.segmented_control( + "Time aggregation", + list(ROLLING_OPTIONS.keys()), + default="7-day average", + label_visibility="collapsed", + ) + + if rolling_label is None: + st.caption("Please select a time aggregation.") + st.stop() + + rolling_window = ROLLING_OPTIONS[rolling_label] + + normalize = st.toggle( + "Normalize", + value=False, + help="Normalize to show percentage share of total requests", + ) + + # Starter kits + with st.expander("Starter kits", expanded=True, icon=":material/auto_awesome:"): + starter_kit = st.pills( + "Quick select", + options=list(STARTER_KITS.keys()), + default="None", + label_visibility="collapsed", + ) + + # Endpoint selection + available_endpoints = API_CATEGORIES[selected_category] + + # Determine default selection based on starter kit + if starter_kit and starter_kit != "None": + default_endpoints = [ + e for e in STARTER_KITS[starter_kit] if e in available_endpoints + ] + else: + default_endpoints = available_endpoints[:4] # First 4 endpoints + + with st.expander("Endpoints", expanded=True, icon=":material/checklist:"): + selected_endpoints = st.multiselect( + "Select endpoints", + options=available_endpoints, + default=default_endpoints, + label_visibility="collapsed", + ) + +# Filter and process data +if not selected_endpoints: + with chart_col: + st.info( + "Select at least one endpoint to view usage data.", icon=":material/info:" + ) + st.stop() + +filtered_data = raw_data[raw_data["endpoint"].isin(selected_endpoints)].copy() +filtered_data = apply_rolling_average(filtered_data, rolling_window) + +if normalize: + filtered_data = normalize_data(filtered_data) + +with chart_col: + # Latest metrics + with st.expander("Latest numbers", expanded=True, icon=":material/numbers:"): + metrics_row = st.container(horizontal=True) + + for endpoint in selected_endpoints: + latest, delta = calculate_delta(filtered_data, endpoint) + + if normalize: + value_str = f"{latest:.2%}" + delta_str = f"{delta:+.2%}" if delta is not None else None + else: + value_str = f"{latest:,.0f}" + delta_str = f"{delta:+,.0f}" if delta is not None else None + + metrics_row.metric( + label=endpoint, + value=value_str, + delta=delta_str, + border=True, + ) + + # Time series chart + with st.expander("Time series", expanded=True, icon=":material/show_chart:"): + y_format = ".1%" if normalize else ",.0f" + y_title = "Share of requests" if normalize else "Request count" + + chart = ( + alt.Chart(filtered_data) + .mark_line() + .encode( + x=alt.X("date:T", title="Date"), + y=alt.Y( + "request_count:Q", title=y_title, axis=alt.Axis(format=y_format) + ), + color=alt.Color( + "endpoint:N", title="Endpoint", legend=alt.Legend(orient="bottom") + ), + tooltip=[ + alt.Tooltip("date:T", title="Date", format="%Y-%m-%d"), + alt.Tooltip("endpoint:N", title="Endpoint"), + alt.Tooltip("request_count:Q", title="Requests", format=y_format), + ], + ) + .properties(height=450) + .interactive() + ) + + st.altair_chart( + chart, + alt=( + f"{rolling_label} share of requests by endpoint over time" + if normalize + else f"{rolling_label} request count by endpoint over time" + ), + ) + +# Raw data section. The expander is collapsed by default, so guard the +# dataframe behind `.open` (enabled by `on_change="rerun"`) to avoid building +# and sending it to the browser until the user actually opens the section. +raw_data_section = st.expander( + "Raw data", expanded=False, icon=":material/table:", on_change="rerun" +) +if raw_data_section.open: + with raw_data_section: + display_df = filtered_data.copy() + column_config = {} + if normalize: + column_config["request_count"] = st.column_config.NumberColumn( + "Requests", format="percent" + ) + st.dataframe( + display_df, + hide_index=True, + column_config=column_config or None, + alt="Filtered endpoint request data", + ) diff --git a/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-metrics/pyproject.toml b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-metrics/pyproject.toml new file mode 100644 index 0000000000..8797860df3 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-metrics/pyproject.toml @@ -0,0 +1,11 @@ +[project] +name = "dashboard-metrics" +version = "1.0.0" +description = "A metrics dashboard template showing time series with sparklines and filtering" +requires-python = ">=3.11" +dependencies = [ + "altair>=5.5.0", + "numpy>=1.26.0", + "pandas>=2.2.3", + "streamlit", +] diff --git a/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-metrics/streamlit_app.py b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-metrics/streamlit_app.py new file mode 100644 index 0000000000..b8f33c6474 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-metrics/streamlit_app.py @@ -0,0 +1,489 @@ +# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Metrics dashboard template. + +Demonstrates: +- KPI row of bordered ``st.metric`` values with deltas and sparklines +- Time series visualization with Altair (line, area, bar, point charts) +- Metric cards with chart/table toggle and popover filters +- Time range filtering (1M, 6M, 1Y, QTD, YTD, All) +- Line options (Daily, 7-day MA) +- ``@st.cache_data(ttl=...)`` per-metric loaders to keep data fresh and bounded +- ``@st.fragment(parallel=True)`` cards that load concurrently on full reruns + and rerun in isolation on widget interactions +- ``st.skeleton`` placeholders so each card fills in as soon as its data is ready + +This template uses synthetic data. Replace the ``generate_*_data()`` functions +with your own data sources (e.g., Snowflake queries, APIs, etc.). +""" + +import hashlib +from datetime import date, timedelta + +import altair as alt +import numpy as np +import pandas as pd + +import streamlit as st + +st.set_page_config( + page_title="Metrics Dashboard", + page_icon=":material/monitoring:", + layout="wide", +) + + +# ============================================================================= +# Constants +# ============================================================================= + +TIME_RANGES = ["1M", "6M", "1Y", "QTD", "YTD", "All"] +CHART_HEIGHT = 300 +KPI_HEIGHT = 215 # Approximate height of a bordered st.metric with a sparkline + +# Per-metric generation settings. Replace with the metrics you actually track. +METRIC_CONFIG: dict[str, dict[str, float]] = { + "users": {"base_value": 5000, "growth_rate": 0.002}, + "sessions": {"base_value": 15000, "growth_rate": 0.003}, + "revenue": {"base_value": 50000, "growth_rate": 0.001}, + "conversions": {"base_value": 500, "growth_rate": 0.0015}, +} + + +# ============================================================================= +# Synthetic Data Generation (Replace with your data source) +# ============================================================================= + + +def generate_metric_data( + metric_name: str, + start_date: date, + end_date: date, + base_value: float = 1000, + growth_rate: float = 0.001, + noise_factor: float = 0.1, +) -> pd.DataFrame: + """Generate synthetic time series data for a metric. + + Replace this function with your actual data source, e.g.: + - Snowflake query + - API call + - Database query + """ + seed = int(hashlib.sha256(metric_name.encode()).hexdigest(), 16) % 2**32 + rng = np.random.default_rng(seed) + + dates = pd.date_range(start=start_date, end=end_date, freq="D") + n_days = len(dates) + + # Base trend with growth + trend = base_value * (1 + growth_rate) ** np.arange(n_days) + + # Add weekly seasonality (lower on weekends) + day_of_week = dates.dayofweek + seasonality = np.where(day_of_week >= 5, 0.7, 1.0) + trend *= seasonality + + # Add noise + noise = rng.normal(1, noise_factor, n_days) + values = trend * noise + + # Calculate rolling averages + df = pd.DataFrame( + { + "ds": dates, + "daily_value": values, + } + ) + df["value_7d_ma"] = df["daily_value"].rolling(7, min_periods=1).mean() + + return df + + +@st.cache_data(ttl="1h", show_spinner=False) +def load_metric(metric_name: str) -> pd.DataFrame: + """Load a single metric's time series (cached per metric). + + Each metric is cached on its own so the metric cards can load + concurrently as parallel fragments. Replace the body with your data + source (Snowflake query, API call, etc.). The ``ttl`` keeps the cache + fresh; add ``max_entries`` if the set of metric names can grow large so + the cache stays bounded. + """ + end_date = date.today() - timedelta(days=1) + start_date = end_date - timedelta(days=730) # 2 years of data + config = METRIC_CONFIG[metric_name] + return generate_metric_data(metric_name, start_date, end_date, **config) + + +# ============================================================================= +# Chart Utilities +# ============================================================================= + + +def filter_by_time_range(df: pd.DataFrame, x_col: str, time_range: str) -> pd.DataFrame: + """Filter dataframe by time range.""" + if time_range == "All" or df.empty: + return df + + df = df.copy() + df[x_col] = pd.to_datetime(df[x_col]) + max_date = df[x_col].max() + + if time_range == "1M": + min_date = max_date - timedelta(days=30) + elif time_range == "6M": + min_date = max_date - timedelta(days=180) + elif time_range == "1Y": + min_date = max_date - timedelta(days=365) + elif time_range == "QTD": + quarter_month = ((max_date.month - 1) // 3) * 3 + 1 + min_date = pd.Timestamp(date(max_date.year, quarter_month, 1)) + elif time_range == "YTD": + min_date = pd.Timestamp(date(max_date.year, 1, 1)) + else: + return df + + filtered: pd.DataFrame = df[df[x_col] >= min_date] + return filtered + + +def _melt_chart_data( + df: pd.DataFrame, x_col: str, y_cols: list[str], labels: list[str] +) -> pd.DataFrame: + """Melt wide data into long form and re-label the series column.""" + melted = df.melt( + id_vars=[x_col], + value_vars=y_cols, + var_name="series", + value_name="value", + ) + label_map = dict(zip(y_cols, labels, strict=True)) + melted["series"] = melted["series"].map(label_map) + return melted + + +def _chart_tooltip(x_col: str, x_title: str = "Date") -> list[alt.Tooltip]: + """Standard tooltip for melted chart data.""" + return [ + alt.Tooltip(f"{x_col}:T", title=x_title, format="%Y-%m-%d"), + alt.Tooltip("series:N", title="Series"), + alt.Tooltip("value:Q", title="Value", format=",.0f"), + ] + + +def render_line_chart( + df: pd.DataFrame, + x_col: str, + y_cols: list[str], + labels: list[str], + height: int = CHART_HEIGHT, +) -> alt.Chart: + """Render a multi-line chart.""" + melted = _melt_chart_data(df, x_col, y_cols, labels) + + chart: alt.Chart = ( + alt.Chart(melted) + .mark_line() + .encode( + x=alt.X(f"{x_col}:T", title=None), + y=alt.Y("value:Q", title=None, scale=alt.Scale(zero=False)), + color=alt.Color("series:N", title=None, legend=alt.Legend(orient="bottom")), + strokeDash=alt.condition( + alt.datum.series == "7-day MA", + alt.value([5, 5]), + alt.value([0]), + ), + tooltip=_chart_tooltip(x_col), + ) + .properties(height=height) + ) + return chart + + +def render_area_chart( + df: pd.DataFrame, + x_col: str, + y_cols: list[str], + labels: list[str], + height: int = CHART_HEIGHT, +) -> alt.Chart: + """Render a stacked area chart.""" + melted = _melt_chart_data(df, x_col, y_cols, labels) + + chart: alt.Chart = ( + alt.Chart(melted) + .mark_area(opacity=0.6, line=True) + .encode( + x=alt.X(f"{x_col}:T", title=None), + y=alt.Y("value:Q", title=None, scale=alt.Scale(zero=False)), + color=alt.Color("series:N", title=None, legend=alt.Legend(orient="bottom")), + tooltip=_chart_tooltip(x_col), + ) + .properties(height=height) + ) + return chart + + +def render_bar_chart( + df: pd.DataFrame, + x_col: str, + y_cols: list[str], + labels: list[str], + height: int = CHART_HEIGHT, +) -> alt.Chart: + """Render a bar chart (weekly aggregation for readability).""" + df = df.copy() + df[x_col] = pd.to_datetime(df[x_col]) + df["week"] = df[x_col].dt.to_period("W").dt.start_time + + agg_df = df.groupby("week")[y_cols].mean().reset_index() + melted = _melt_chart_data(agg_df, "week", y_cols, labels) + + chart: alt.Chart = ( + alt.Chart(melted) + .mark_bar(opacity=0.8) + .encode( + x=alt.X("week:T", title=None), + y=alt.Y("value:Q", title=None, scale=alt.Scale(zero=False)), + color=alt.Color("series:N", title=None, legend=alt.Legend(orient="bottom")), + xOffset="series:N", + tooltip=_chart_tooltip("week", x_title="Week"), + ) + .properties(height=height) + ) + return chart + + +def render_point_chart( + df: pd.DataFrame, + x_col: str, + y_cols: list[str], + labels: list[str], + height: int = CHART_HEIGHT, +) -> alt.Chart: + """Render a scatter/point chart with a dashed trend line for the 7-day MA.""" + melted = _melt_chart_data(df, x_col, y_cols, labels) + + points = ( + alt.Chart(melted) + .mark_point(opacity=0.5, size=20) + .encode( + x=alt.X(f"{x_col}:T", title=None), + y=alt.Y("value:Q", title=None, scale=alt.Scale(zero=False)), + color=alt.Color("series:N", title=None, legend=alt.Legend(orient="bottom")), + tooltip=_chart_tooltip(x_col), + ) + ) + + trend = ( + alt.Chart(melted[melted["series"] == "7-day MA"]) + .mark_line(strokeDash=[5, 5], strokeWidth=2) + .encode( + x=alt.X(f"{x_col}:T"), + y=alt.Y("value:Q"), + color=alt.Color("series:N"), + ) + ) + + chart: alt.Chart = (points + trend).properties(height=height) + return chart + + +# ============================================================================= +# KPI Card Component +# ============================================================================= + + +@st.fragment(parallel=True) +def kpi_card(label: str, metric_name: str) -> None: + """Display a bordered KPI card: the latest 7-day average and its 4-week change. + + Like the metric cards, each KPI is a parallel fragment that loads its own + (cached) data inside ``st.skeleton``. + """ + with st.skeleton(height=KPI_HEIGHT): + # The last 4 weeks (29 daily points) of the 7-day average: the value is + # the latest point, the delta compares it to the first one. + trend = load_metric(metric_name)["value_7d_ma"].tail(29) + change = round(trend.iloc[-1] / trend.iloc[0] - 1, 3) + st.metric( + label, + f"{trend.iloc[-1]:,.0f}", + # String deltas like "+0.0%" still get an arrow; pass 0 when flat. + f"{change:+.1%}" if change else 0, + delta_description="vs. 4 weeks ago", + help="7-day average", + chart_data=trend, + border=True, + ) + + +# ============================================================================= +# Metric Card Component +# ============================================================================= + + +@st.fragment(parallel=True) +def metric_card( + title: str, + metric_name: str, + chart_type: str = "line", +) -> None: + """Display a metric card with chart/table toggle and popover filters. + + The card is a parallel fragment: on a full app rerun every card loads its + own data concurrently, and on widget interactions (view toggle, filters) + only this card reruns. The card's data is loaded inside ``st.skeleton`` so + the title and controls stay stable while the chart fills in. + + Parameters + ---------- + title : str + Card title. + metric_name : str + Key into ``METRIC_CONFIG`` used to load this card's data and namespace + this card's widget state. + chart_type : str + One of ``"line"``, ``"area"``, ``"bar"``, ``"point"``. + """ + chart_renderers = { + "line": render_line_chart, + "area": render_area_chart, + "bar": render_bar_chart, + "point": render_point_chart, + } + render_chart = chart_renderers.get(chart_type, render_line_chart) + + with st.container(border=True): + # Header row with title, view toggle, and filters. Keep it outside the + # skeleton so the controls stay put while the chart loads. + with st.container( + horizontal=True, + horizontal_alignment="distribute", + vertical_alignment="center", + ): + st.markdown(f"**{title}**") + + view_mode = st.segmented_control( + "View", + options=[":material/show_chart:", ":material/table:"], + default=":material/show_chart:", + key=f"{metric_name}_view", + label_visibility="collapsed", + ) + + with st.popover("Filters", type="tertiary"): + line_options = st.pills( + "Lines", + options=["Daily", "7-day MA"], + default=["Daily", "7-day MA"], + selection_mode="multi", + key=f"{metric_name}_lines", + ) + time_range = st.segmented_control( + "Time range", + options=TIME_RANGES, + default="All", + key=f"{metric_name}_time", + ) + + # Load this card's data and render inside a skeleton placeholder. The + # skeleton shows while the (cached) loader runs, then clears once the + # chart or table is rendered. + with st.skeleton(height=CHART_HEIGHT): + df = load_metric(metric_name) + + # Apply filters + line_options = line_options or ["7-day MA"] + filtered_df = filter_by_time_range(df, "ds", time_range or "All") + + # Determine which columns to show + y_cols = [] + labels = [] + if "Daily" in line_options: + y_cols.append("daily_value") + labels.append("Daily") + if "7-day MA" in line_options: + y_cols.append("value_7d_ma") + labels.append("7-day MA") + + # Render view + if "table" in (view_mode or ""): + st.dataframe( + filtered_df, + height=CHART_HEIGHT, + hide_index=True, + alt=f"{title} data", + ) + elif y_cols: + st.altair_chart( + render_chart(filtered_df, "ds", y_cols, labels), + alt=f"{title} over time", + ) + else: + st.info("Select at least one line option.") + + +# ============================================================================= +# Page Header Component +# ============================================================================= + + +def render_page_header(title: str) -> None: + """Render page header with title and reset button.""" + with st.container( + horizontal=True, horizontal_alignment="distribute", vertical_alignment="center" + ): + st.markdown(title) + if st.button(":material/restart_alt: Reset", type="tertiary"): + st.session_state.clear() + st.rerun() + + +# ============================================================================= +# Page Layout +# ============================================================================= + +# Page header +render_page_header("# :material/monitoring: Metrics Dashboard") + +# Each KPI and card loads its own data; as parallel fragments they load +# concurrently on the first run instead of blocking on each other. + +# KPI row: horizontal containers wrap on narrow screens. +with st.container(horizontal=True): + kpi_card("Active users", "users") + kpi_card("Sessions", "sessions") + kpi_card("Revenue", "revenue") + kpi_card("Conversions", "conversions") + +# Row 1: Users and Sessions +row1 = st.columns(2) + +with row1[0]: + metric_card("Active users", "users", chart_type="line") + +with row1[1]: + metric_card("Sessions", "sessions", chart_type="area") + +# Row 2: Revenue and Conversions +row2 = st.columns(2) + +with row2[0]: + metric_card("Revenue", "revenue", chart_type="bar") + +with row2[1]: + metric_card("Conversions", "conversions", chart_type="point") diff --git a/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-seattle-weather/pyproject.toml b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-seattle-weather/pyproject.toml new file mode 100644 index 0000000000..3f1827a505 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-seattle-weather/pyproject.toml @@ -0,0 +1,11 @@ +[project] +name = "dashboard-seattle-weather" +version = "1.0.0" +description = "An example dashboard exploring the Seattle Weather dataset" +requires-python = ">=3.11" +dependencies = [ + "altair>=5.5.0", + "pandas>=2.2.3", + "streamlit", + "vega-datasets>=0.9.0", +] diff --git a/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-seattle-weather/streamlit_app.py b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-seattle-weather/streamlit_app.py new file mode 100644 index 0000000000..2c1ea14b22 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-seattle-weather/streamlit_app.py @@ -0,0 +1,274 @@ +# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Seattle Weather dashboard exploring the classic Altair case study dataset.""" + +import altair as alt +import pandas as pd +import vega_datasets + +import streamlit as st + +st.set_page_config( + # Title and icon for the browser's tab bar: + page_title="Seattle Weather", + page_icon=":material/wb_sunny:", + # Make the content take up the width of the page: + layout="wide", +) + + +@st.cache_data(show_spinner="Loading weather data...") +def load_weather_data() -> pd.DataFrame: + df: pd.DataFrame = vega_datasets.data("seattle_weather") + return df + + +full_df = load_weather_data() + +""" +# Seattle Weather + +Let's explore the [classic Seattle Weather +dataset](https://altair-viz.github.io/case_studies/exploring-weather.html)! +""" + +st.space("medium") + +""" +## 2015 Summary +""" + +st.space("small") + +df_2015 = full_df[full_df["date"].dt.year == 2015] +df_2014 = full_df[full_df["date"].dt.year == 2014] + +max_temp_2015 = df_2015["temp_max"].max() +max_temp_2014 = df_2014["temp_max"].max() + +min_temp_2015 = df_2015["temp_min"].min() +min_temp_2014 = df_2014["temp_min"].min() + +max_wind_2015 = df_2015["wind"].max() +max_wind_2014 = df_2014["wind"].max() + +min_wind_2015 = df_2015["wind"].min() +min_wind_2014 = df_2014["wind"].min() + +max_prec_2015 = df_2015["precipitation"].max() +max_prec_2014 = df_2014["precipitation"].max() + +min_prec_2015 = df_2015["precipitation"].min() +min_prec_2014 = df_2014["precipitation"].min() + + +with st.container(horizontal=True, gap="medium"): + cols = st.columns(2, gap="medium", width=300) + + with cols[0]: + st.metric( + "Max temperature", + f"{max_temp_2015:0.1f}C", + delta=f"{max_temp_2015 - max_temp_2014:0.1f}C", + width="content", + ) + + with cols[1]: + st.metric( + "Min temperature", + f"{min_temp_2015:0.1f}C", + delta=f"{min_temp_2015 - min_temp_2014:0.1f}C", + width="content", + ) + + cols = st.columns(2, gap="medium", width=300) + + with cols[0]: + st.metric( + "Max precipitation", + f"{max_prec_2015:0.1f}mm", + delta=f"{max_prec_2015 - max_prec_2014:0.1f}mm", + width="content", + ) + + with cols[1]: + st.metric( + "Min precipitation", + f"{min_prec_2015:0.1f}mm", + delta=f"{min_prec_2015 - min_prec_2014:0.1f}mm", + width="content", + ) + + cols = st.columns(2, gap="medium", width=300) + + with cols[0]: + st.metric( + "Max wind", + f"{max_wind_2015:0.1f}m/s", + delta=f"{max_wind_2015 - max_wind_2014:0.1f}m/s", + width="content", + ) + + with cols[1]: + st.metric( + "Min wind", + f"{min_wind_2015:0.1f}m/s", + delta=f"{min_wind_2015 - min_wind_2014:0.1f}m/s", + width="content", + ) + + weather_icons = { + "sun": "sunny", + "snow": "weather_snowy", + "rain": "rainy", + "fog": "foggy", + "drizzle": "rainy", + } + + cols = st.columns(2, gap="large") + + with cols[0]: + weather_name = ( + full_df["weather"].value_counts().head(1).reset_index()["weather"][0] + ) + st.metric( + "Most common weather", + f":material/{weather_icons[weather_name]}: {weather_name.upper()}", + ) + + with cols[1]: + weather_name = ( + full_df["weather"].value_counts().tail(1).reset_index()["weather"][0] + ) + st.metric( + "Least common weather", + f":material/{weather_icons[weather_name]}: {weather_name.upper()}", + ) + +st.space("medium") + +""" +## Compare different years +""" + +YEARS = full_df["date"].dt.year.unique() +selected_years = st.pills( + "Years to compare", YEARS, default=YEARS, selection_mode="multi" +) + +if not selected_years: + st.warning("You must select at least 1 year.", icon=":material/warning:") + st.stop() + +df = full_df[full_df["date"].dt.year.isin(selected_years)] + +cols = st.columns([3, 1]) + +with cols[0].container(border=True, height="stretch"): + "### :material/thermostat: Temperature" + + st.altair_chart( + alt.Chart(df) + .mark_bar(width=1) + .encode( + alt.X("monthdate(date):T").title("date"), + alt.Y("temp_max:Q").title("temperature range (C)"), + alt.Y2("temp_min:Q"), + alt.Color("year(date):N").title("year"), + alt.XOffset("year(date):N"), + tooltip=[ + alt.Tooltip("monthdate(date):T", title="Date"), + alt.Tooltip("temp_max:Q", title="Max Temp (C)"), + alt.Tooltip("temp_min:Q", title="Min Temp (C)"), + alt.Tooltip("year(date):N", title="Year"), + ], + ) + .configure_legend(orient="bottom"), + alt="Daily high and low temperatures by year", + ) + +with cols[1].container(border=True, height="stretch"): + "### Weather distribution" + + st.altair_chart( + alt.Chart(df) + .mark_arc() + .encode( + alt.Theta("count()"), + alt.Color("weather:N"), + ) + .configure_legend(orient="bottom"), + alt="Share of days by weather type", + ) + + +cols = st.columns(2) + +with cols[0].container(border=True, height="stretch"): + "### :material/air: Wind" + + # Prepare data for st.line_chart - pivot by year + wind_df = df.copy() + wind_df["month_day"] = wind_df["date"].dt.strftime("%m-%d") + wind_df["year"] = wind_df["date"].dt.year + + # Pivot to one column per year (mean wind per calendar day) + wind_pivot = wind_df.pivot_table( + index="month_day", columns="year", values="wind", aggfunc="mean" + ).sort_index() + + st.line_chart(wind_pivot, height=300, alt="Average wind speed by day of year") + +with cols[1].container(border=True, height="stretch"): + "### :material/water_drop: Precipitation" + + st.altair_chart( + alt.Chart(df) + .mark_bar() + .encode( + alt.X("month(date):O").title("month"), + alt.Y("sum(precipitation):Q").title("precipitation (mm)"), + alt.Color("year(date):N").title("year"), + tooltip=[ + alt.Tooltip("month(date):O", title="Month"), + alt.Tooltip("sum(precipitation):Q", title="Precipitation (mm)"), + alt.Tooltip("year(date):N", title="Year"), + ], + ) + .configure_legend(orient="bottom"), + alt="Monthly precipitation totals by year", + ) + +cols = st.columns(2) + +with cols[0].container(border=True, height="stretch"): + "### :material/calendar_month: Monthly weather breakdown" + + st.altair_chart( + alt.Chart(df) + .mark_bar() + .encode( + alt.X("month(date):O", title="month"), + alt.Y("count():Q", title="days", stack="normalize"), + alt.Color("weather:N"), + ) + .configure_legend(orient="bottom"), + alt="Monthly mix of weather types", + ) + +with cols[1].container(border=True, height="stretch"): + "### :material/table: Raw data" + + st.dataframe(df, hide_index=True, alt="Seattle weather observations") diff --git a/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-stock-peers/pyproject.toml b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-stock-peers/pyproject.toml new file mode 100644 index 0000000000..7b0ecd761e --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-stock-peers/pyproject.toml @@ -0,0 +1,11 @@ +[project] +name = "dashboard-stock-peers" +version = "1.0.0" +description = "Stock peer analysis dashboard: easily compare stocks against others in their peer group" +requires-python = ">=3.11" +dependencies = [ + "altair>=5.5.0", + "pandas>=2.2.3", + "streamlit", + "yfinance>=0.2.55", +] diff --git a/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-stock-peers/streamlit_app.py b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-stock-peers/streamlit_app.py new file mode 100644 index 0000000000..71cf3d729f --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/apps/dashboard-stock-peers/streamlit_app.py @@ -0,0 +1,346 @@ +# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Stock peer analysis dashboard for comparing a set of tickers over time.""" + +from collections.abc import Iterable + +import altair as alt +import pandas as pd +import yfinance as yf + +import streamlit as st + +st.set_page_config( + page_title="Stock peer analysis dashboard", + page_icon=":material/query_stats:", + layout="wide", +) + +""" +# :material/query_stats: Stock peer analysis + +Easily compare stocks against others in their peer group. +""" + +st.space("small") +cols = st.columns([1, 3]) +# Will declare right cell later to avoid showing it when no data. + +STOCKS = [ + "AAPL", + "ABBV", + "ACN", + "ADBE", + "ADP", + "AMD", + "AMGN", + "AMT", + "AMZN", + "APD", + "AVGO", + "AXP", + "BA", + "BK", + "BKNG", + "BMY", + "BRK.B", + "BSX", + "C", + "CAT", + "CI", + "CL", + "CMCSA", + "COST", + "CRM", + "CSCO", + "CVX", + "DE", + "DHR", + "DIS", + "DUK", + "ELV", + "EOG", + "EQR", + "FDX", + "GD", + "GE", + "GILD", + "GOOG", + "GOOGL", + "HD", + "HON", + "HUM", + "IBM", + "ICE", + "INTC", + "ISRG", + "JNJ", + "JPM", + "KO", + "LIN", + "LLY", + "LMT", + "LOW", + "MA", + "MCD", + "MDLZ", + "META", + "MMC", + "MO", + "MRK", + "MSFT", + "NEE", + "NFLX", + "NKE", + "NOW", + "NVDA", + "ORCL", + "PEP", + "PFE", + "PG", + "PLD", + "PM", + "PSA", + "REGN", + "RTX", + "SBUX", + "SCHW", + "SLB", + "SO", + "SPGI", + "T", + "TJX", + "TMO", + "TSLA", + "TXN", + "UNH", + "UNP", + "UPS", + "V", + "VZ", + "WFC", + "WM", + "WMT", + "XOM", +] + +DEFAULT_STOCKS = ["AAPL", "MSFT", "GOOGL", "NVDA", "AMZN", "TSLA", "META"] + + +top_left_cell = cols[0].container( + border=True, height="stretch", vertical_alignment="center" +) + +with top_left_cell: + # Multiselect for stock tickers. bind="query-params" keeps the selection in + # the URL so the dashboard is shareable — no manual st.query_params plumbing. + tickers = st.multiselect( + "Stock tickers", + options=STOCKS, + default=DEFAULT_STOCKS, + key="stocks", # repeated params: ?stocks=AAPL&stocks=MSFT + bind="query-params", + placeholder="Choose stocks to compare. Example: NVDA", + accept_new_options=True, + ) + +# Time horizon selector +horizon_map = { + "1 Month": "1mo", + "3 Months": "3mo", + "6 Months": "6mo", + "1 Year": "1y", + "5 Years": "5y", + "10 Years": "10y", + "20 Years": "20y", +} + +with top_left_cell: + # Buttons for picking time horizon + horizon = st.pills( + "Time horizon", + options=list(horizon_map.keys()), + default="6 Months", + ) + +# `st.pills` returns None if the user deselects the active pill. Stop early +# so we don't hit a KeyError when looking up `horizon_map[horizon]` below. +if horizon is None: + top_left_cell.info("Pick a time horizon", icon=":material/info:") + st.stop() + +tickers = [t.upper() for t in tickers] + +if not tickers: + top_left_cell.info("Pick some stocks to compare", icon=":material/info:") + st.stop() + + +right_cell = cols[1].container( + border=True, height="stretch", vertical_alignment="center" +) + + +@st.cache_data(ttl="6h", show_spinner="Loading stock price data...") +def load_data(tickers: Iterable[str], period: str) -> pd.DataFrame: + tickers_obj = yf.Tickers(list(tickers)) + data = tickers_obj.history(period=period) + if data is None: + raise RuntimeError("YFinance returned no data.") + close_prices: pd.DataFrame = data["Close"] + return close_prices + + +# Load the data +try: + data = load_data(tickers, horizon_map[horizon]) +except yf.exceptions.YFRateLimitError: + st.warning("YFinance is rate-limiting us :(\nTry again later.") + st.stop() + raise # Unreachable — st.stop() halts execution, but helps type checker. + +empty_columns = data.columns[data.isna().all()].tolist() + +if empty_columns: + st.error(f"Error loading data for the tickers: {', '.join(empty_columns)}.") + st.stop() + +# Normalize prices (start at 1). Use the first non-null value per ticker so +# tickers whose first row is NaN (e.g. newer listings over a long horizon) +# don't get normalized to NaN. +normalized = data.div(data.bfill().iloc[0]) + +# Build list of (normalized_value, ticker) tuples for safe comparison +# (using a dict with float keys could silently drop tickers with identical values). +ticker_values = [(normalized[ticker].iloc[-1], ticker) for ticker in tickers] +max_norm_value = max(ticker_values) +min_norm_value = min(ticker_values) + +bottom_left_cell = cols[0].container( + border=True, height="stretch", vertical_alignment="center" +) + +with bottom_left_cell: + cols = st.columns(2) + cols[0].metric( + "Best stock", + max_norm_value[1], + delta=f"{round((max_norm_value[0] - 1) * 100)}%", + width="content", + ) + cols[1].metric( + "Worst stock", + min_norm_value[1], + delta=f"{round((min_norm_value[0] - 1) * 100)}%", + width="content", + ) + + +# Plot normalized prices +with right_cell: + st.altair_chart( + alt.Chart( + normalized.reset_index().melt( + id_vars=["Date"], var_name="Stock", value_name="Normalized price" + ) + ) + .mark_line() + .encode( + alt.X("Date:T"), + alt.Y("Normalized price:Q").scale(zero=False), + alt.Color("Stock:N"), + ) + .properties(height=400), + alt="Normalized stock prices over time", + ) + +st.space("medium") + +# Plot individual stock vs peer average +""" +## Individual stocks vs peer average + +For the analysis below, the "peer average" when analyzing stock X always +excludes X itself. +""" + +if len(tickers) <= 1: + st.warning("Pick 2 or more tickers to compare them") + st.stop() + +NUM_COLS = 4 +cols = st.columns(NUM_COLS) + +for i, ticker in enumerate(tickers): + # Calculate peer average (excluding current stock) + peers = normalized.drop(columns=[ticker]) + peer_avg = peers.mean(axis=1) + + # Create DataFrame with peer average. + plot_data = pd.DataFrame( + { + "Date": normalized.index, + ticker: normalized[ticker], + "Peer average": peer_avg, + } + ).melt(id_vars=["Date"], var_name="Series", value_name="Price") + + chart = ( + alt.Chart(plot_data) + .mark_line() + .encode( + alt.X("Date:T"), + alt.Y("Price:Q").scale(zero=False), + alt.Color( + "Series:N", + scale=alt.Scale(domain=[ticker, "Peer average"], range=["red", "gray"]), + legend=alt.Legend(orient="bottom"), + ), + alt.Tooltip(["Date", "Series", "Price"]), + ) + .properties(title=f"{ticker} vs peer average", height=300) + ) + + cell = cols[(i * 2) % NUM_COLS].container(border=True) + cell.altair_chart(chart, alt=f"{ticker} versus peer-average price") + + # Create Delta chart + plot_data = pd.DataFrame( + { + "Date": normalized.index, + "Delta": normalized[ticker] - peer_avg, + } + ) + + chart = ( + alt.Chart(plot_data) + .mark_area() + .encode( + alt.X("Date:T"), + alt.Y("Delta:Q").scale(zero=False), + ) + .properties(title=f"{ticker} minus peer average", height=300) + ) + + cell = cols[(i * 2 + 1) % NUM_COLS].container(border=True) + cell.altair_chart(chart, alt=f"{ticker} price gap versus peer average") + +st.space("medium") + +""" +## Raw data +""" + +st.dataframe(data, alt="Selected stock price history") diff --git a/.agents/skills/developing-with-streamlit/assets/templates/themes/README.md b/.agents/skills/developing-with-streamlit/assets/templates/themes/README.md new file mode 100644 index 0000000000..830611d28b --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/themes/README.md @@ -0,0 +1,50 @@ +# Streamlit theme templates + +Ready-to-use theme configs. Each file in `configs/` is a complete theme +block — paste into your app's `.streamlit/config.toml`, or adapt into a +shared brand file and point each app’s `theme.base` at it. + +When several apps share a brand, put cross-app brand keys (colors, fonts, +radii, borders, chart/dataframe palettes) in one `theme.base` file and +override per app. Keep app-specific layout tweaks (padding, denser +sidebar, one-off primary) in each app’s `config.toml`. Streamlit resolves +a relative `theme.base` path from the `streamlit run` working directory, +not from `config.toml`. For a single app, copy a template straight into +`.streamlit/config.toml`. Choose single or dual mode from the goal below; +use dual mode only when users should control appearance. + +| Goal | Approach | +|------|----------| +| Same brand across many apps | Shared TOML/URL via `theme.base`; tweak in each app’s `config.toml` | +| Locked single look | Single-mode template or `[theme]` only | +| User can toggle light/dark | Dual-mode template (`shadcn-dual`, `dense-dashboard`) | + +## Dual-mode (settings toggle stays available) + +| Theme | Modes | Primary | Notes | +|-------|-------|---------|-------| +| **shadcn-dual** | Light + dark | `#18181B` / `#71717A` | Neutral brand look with per-mode sidebars | +| **dense-dashboard** | Light + dark | `#1D4ED8` / `#2563EB` | Compact `paddingTop`/`paddingBottom` for KPI dashboards | + +## Single-mode (locked appearance) + +| Theme | Base | Primary color | Fonts | +|-------|------|---------------|-------| +| **dracula** | Dark | `#BD93F9` (purple) | Fira Sans, JetBrains Mono | +| **financial-dashboard** | Dark | `#60A5FA` (blue) | Inter, JetBrains Mono | +| **fluent** | Light | `#0078D4` (blue) | Segoe UI, Cascadia Code | +| **jupyter** | Light | `#F37626` (orange) | Source Sans 3, Source Code Pro | +| **material-ui** | Light | `#6750A4` (violet) | Roboto, Roboto Mono | +| **minimal** | Dark | `#6366F1` (indigo) | Inter, JetBrains Mono | +| **nord** | Dark | `#88C0D0` (frost blue) | Inter, JetBrains Mono | +| **one-dark-pro** | Dark | `#61AFEF` (blue) | IBM Plex Sans, JetBrains Mono | +| **shadcn** | Light | `#18181B` (zinc) | Inter, JetBrains Mono | +| **solarized-light** | Light | `#268BD2` (blue) | Source Sans 3, Source Code Pro | +| **ubuntu** | Light | `#E95420` (orange) | Ubuntu, Ubuntu Mono | +| **vscode** | Dark | `#0078D4` (blue) | Segoe UI, Fira Code | + +All themes load [Google Fonts](https://fonts.google.com/) via the +`font = ":"` syntax — no local font files required. + +See `references/theme.md` for shared `theme.base` inheritance, light/dark +sections, padding, and the full theming guide. diff --git a/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/dense-dashboard.toml b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/dense-dashboard.toml new file mode 100644 index 0000000000..8370a4037f --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/dense-dashboard.toml @@ -0,0 +1,125 @@ +# Dense dual-mode dashboard theme +# Compact padding for KPI layouts; settings appearance toggle stays available + +[theme] +showWidgetBorder = true +showSidebarBorder = true +baseRadius = "6px" +buttonRadius = "6px" +font = "'Inter':https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" +headingFont = "'Inter':https://fonts.googleapis.com/css2?family=Inter:wght@600;700&display=swap" +codeFont = "'JetBrains Mono':https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500&display=swap" +baseFontSize = 14 +baseFontWeight = 400 +codeFontSize = "13px" +headingFontSizes = ["28px", "22px", "18px", "16px", "14px", "12px"] +headingFontWeights = [700, 600, 600, 600, 500, 500] +linkUnderline = false +paddingTop = "0.5rem" +paddingBottom = "3rem" + +[theme.light] +primaryColor = "#1D4ED8" +backgroundColor = "#FFFFFF" +secondaryBackgroundColor = "#F1F5F9" +codeBackgroundColor = "#F1F5F9" +textColor = "#0F172A" +linkColor = "#1D4ED8" +borderColor = "#CBD5E1" +codeTextColor = "#334155" +greenColor = "#059669" +redColor = "#DC2626" +yellowColor = "#D97706" +orangeColor = "#EA580C" +blueColor = "#1D4ED8" +violetColor = "#7C3AED" +grayColor = "#64748B" +chartCategoricalColors = [ + "#1D4ED8", + "#059669", + "#7C3AED", + "#DC2626", + "#D97706", + "#0284C7", + "#64748B", + "#EA580C", +] +chartSequentialColors = [ + "#F0F9FF", + "#E0F2FE", + "#BAE6FD", + "#7DD3FC", + "#38BDF8", + "#0EA5E9", + "#0284C7", + "#0369A1", + "#075985", + "#0C4A6E", +] +dataframeBorderColor = "#CBD5E1" +dataframeHeaderBackgroundColor = "#E2E8F0" +dataframeHeaderTextColor = "#0F172A" + +[theme.dark] +primaryColor = "#2563EB" +backgroundColor = "#0F172A" +secondaryBackgroundColor = "#1E293B" +codeBackgroundColor = "#1E293B" +textColor = "#F1F5F9" +linkColor = "#60A5FA" +borderColor = "#334155" +codeTextColor = "#CBD5E1" +greenColor = "#34D399" +redColor = "#F87171" +yellowColor = "#FBBF24" +orangeColor = "#FB923C" +blueColor = "#60A5FA" +violetColor = "#A78BFA" +grayColor = "#94A3B8" +chartCategoricalColors = [ + "#60A5FA", + "#34D399", + "#A78BFA", + "#F87171", + "#FBBF24", + "#38BDF8", + "#94A3B8", + "#FB923C", +] +chartSequentialColors = [ + "#0C4A6E", + "#075985", + "#0369A1", + "#0284C7", + "#0EA5E9", + "#38BDF8", + "#7DD3FC", + "#BAE6FD", + "#E0F2FE", + "#F0F9FF", +] +dataframeBorderColor = "#334155" +dataframeHeaderBackgroundColor = "#1E293B" +dataframeHeaderTextColor = "#F8FAFC" + +[theme.sidebar] +paddingTop = "0.5rem" +paddingBottom = "1.5rem" + +[theme.light.sidebar] +backgroundColor = "#FFFFFF" +secondaryBackgroundColor = "#F1F5F9" +codeBackgroundColor = "#E2E8F0" +textColor = "#0F172A" +borderColor = "#CBD5E1" +primaryColor = "#1D4ED8" +linkColor = "#1D4ED8" + +[theme.dark.sidebar] +backgroundColor = "#020617" +secondaryBackgroundColor = "#1E293B" +codeBackgroundColor = "#1E293B" +textColor = "#F1F5F9" +borderColor = "#334155" +primaryColor = "#2563EB" +linkColor = "#60A5FA" diff --git a/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/dracula.toml b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/dracula.toml new file mode 100644 index 0000000000..1b4773b2a2 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/dracula.toml @@ -0,0 +1,39 @@ +# Dracula Theme for Streamlit +# Popular dark theme with vibrant colors on dark background +[theme] +base = "dark" +primaryColor = "#bd93f9" +backgroundColor = "#282a36" +secondaryBackgroundColor = "#21222c" +codeBackgroundColor = "#21222c" +textColor = "#f8f8f2" +linkColor = "#8be9fd" +borderColor = "#44475a" +showWidgetBorder = true +showSidebarBorder = true +baseRadius = "8px" +buttonRadius = "8px" +font = "'Fira Sans':https://fonts.googleapis.com/css2?family=Fira+Sans:wght@400;500;600;700&display=swap" +codeFont = "'JetBrains Mono':https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500&display=swap" +codeFontSize = "0.875rem" +codeTextColor = "#f8f8f2" +baseFontSize = 14 +baseFontWeight = 400 +headingFontSizes = ["32px", "24px", "20px", "16px", "14px", "12px"] +headingFontWeights = [700, 600, 600, 600, 600, 600] +linkUnderline = false +chartCategoricalColors = ["#bd93f9", "#50fa7b", "#ff79c6", "#8be9fd", "#ffb86c", "#ff5555", "#f1fa8c"] + +# Dracula color palette +violetColor = "#bd93f9" +greenColor = "#50fa7b" +redColor = "#ff5555" +blueColor = "#8be9fd" +yellowColor = "#f1fa8c" +orangeColor = "#ffb86c" + +[theme.sidebar] +backgroundColor = "#21222c" +secondaryBackgroundColor = "#191a21" +codeBackgroundColor = "#191a21" +borderColor = "#44475a" diff --git a/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/financial-dashboard.toml b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/financial-dashboard.toml new file mode 100644 index 0000000000..d63f8f2555 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/financial-dashboard.toml @@ -0,0 +1,77 @@ +# Professional Financial Dashboard Theme (Dark) +# Conservative, trustworthy palette with clear data visualization + +[theme] +base = "dark" +primaryColor = "#60A5FA" # Bright blue for dark mode +backgroundColor = "#0F172A" # Deep slate +secondaryBackgroundColor = "#1E293B" # Slightly lighter slate +codeBackgroundColor = "#1E293B" +textColor = "#F1F5F9" # Light text +linkColor = "#60A5FA" +borderColor = "#334155" +codeTextColor = "#CBD5E1" +showWidgetBorder = true +showSidebarBorder = true +baseRadius = "6px" # Subtle rounding - professional, not playful +buttonRadius = "6px" + +# Typography - Clean, professional fonts +font = "'Inter':https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" +headingFont = "'Inter':https://fonts.googleapis.com/css2?family=Inter:wght@600;700&display=swap" +codeFont = "'JetBrains Mono':https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500&display=swap" +baseFontSize = 14 +baseFontWeight = 400 +codeFontSize = "13px" +headingFontSizes = ["28px", "22px", "18px", "16px", "14px", "12px"] +headingFontWeights = [700, 600, 600, 600, 500, 500] +linkUnderline = false + +# Semantic colors for financial indicators +greenColor = "#34D399" # Positive/gains - bright green +redColor = "#F87171" # Negative/losses - bright red +yellowColor = "#FBBF24" # Warnings/caution +orangeColor = "#FB923C" # Alerts +blueColor = "#60A5FA" # Informational +violetColor = "#A78BFA" # Accent/highlights +grayColor = "#94A3B8" # Neutral/secondary text + +# Chart colors - Distinguishable palette for financial data +chartCategoricalColors = [ + "#60A5FA", + "#34D399", + "#A78BFA", + "#F87171", + "#FBBF24", + "#38BDF8", + "#94A3B8", + "#FB923C", +] + +# Sequential colors for heatmaps (blue gradient) +chartSequentialColors = [ + "#0C4A6E", + "#075985", + "#0369A1", + "#0284C7", + "#0EA5E9", + "#38BDF8", + "#7DD3FC", + "#BAE6FD", + "#E0F2FE", + "#F0F9FF", +] + +# Dataframe styling +dataframeBorderColor = "#334155" +dataframeHeaderBackgroundColor = "#1E293B" +dataframeHeaderTextColor = "#F8FAFC" + +# Sidebar +[theme.sidebar] +backgroundColor = "#0F172A" +secondaryBackgroundColor = "#1E293B" +codeBackgroundColor = "#1E293B" +textColor = "#F1F5F9" +borderColor = "#334155" +primaryColor = "#60A5FA" diff --git a/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/fluent.toml b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/fluent.toml new file mode 100644 index 0000000000..d7d6562ce2 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/fluent.toml @@ -0,0 +1,49 @@ +# Microsoft Fluent Design-inspired Streamlit Theme +# Modern Windows 11 aesthetic +# Light, airy with depth and acrylic-like elements + +[theme] +base = "light" +primaryColor = "#0078D4" +backgroundColor = "#FFFFFF" +secondaryBackgroundColor = "#F5F5F5" +codeBackgroundColor = "#F3F3F3" +textColor = "#1A1A1A" +linkColor = "#0078D4" +borderColor = "#E0E0E0" +showWidgetBorder = true +showSidebarBorder = false +baseRadius = "4px" +buttonRadius = "4px" +font = "'Segoe UI', 'Open Sans':https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;500;600;700&display=swap" +codeFont = "'Cascadia Code', 'Fira Code':https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;500&display=swap" +codeFontSize = "0.875rem" +codeTextColor = "#1A1A1A" +baseFontSize = 14 +baseFontWeight = 400 +headingFontSizes = ["28px", "24px", "20px", "16px", "14px", "12px"] +headingFontWeights = [600, 600, 600, 600, 600, 600] +linkUnderline = false +chartCategoricalColors = ["#0078D4", "#107C10", "#D83B01", "#FFB900", "#8764B8", "#00B7C3", "#E81123"] + +# Fluent accent colors +blueColor = "#0078D4" +greenColor = "#107C10" +redColor = "#E81123" +yellowColor = "#FFB900" +orangeColor = "#D83B01" +violetColor = "#8764B8" +grayColor = "#737373" + +dataframeBorderColor = "#E0E0E0" +dataframeHeaderBackgroundColor = "#F5F5F5" + +[theme.sidebar] +backgroundColor = "#F3F3F3" +secondaryBackgroundColor = "#EBEBEB" +codeBackgroundColor = "#E5E5E5" +textColor = "#1A1A1A" +borderColor = "#D1D1D1" +primaryColor = "#0078D4" +dataframeHeaderBackgroundColor = "#EBEBEB" +dataframeBorderColor = "#D1D1D1" diff --git a/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/jupyter.toml b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/jupyter.toml new file mode 100644 index 0000000000..bd66bee0f0 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/jupyter.toml @@ -0,0 +1,49 @@ +# Jupyter-inspired Streamlit Theme +# Interactive computing aesthetic +# Notebook-style with signature orange and clean cells + +[theme] +base = "light" +primaryColor = "#F37626" +backgroundColor = "#FFFFFF" +secondaryBackgroundColor = "#F7F7F7" +codeBackgroundColor = "#F7F7F7" +textColor = "#212121" +linkColor = "#2196F3" +borderColor = "#E0E0E0" +showWidgetBorder = true +showSidebarBorder = true +baseRadius = "2px" +buttonRadius = "2px" +font = "'Source Sans 3':https://fonts.googleapis.com/css2?family=Source+Sans+3:wght@300;400;500;600;700&display=swap" +codeFont = "'Source Code Pro':https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght@400;500&display=swap" +codeFontSize = "0.875rem" +codeTextColor = "#212121" +baseFontSize = 14 +baseFontWeight = 400 +headingFontSizes = ["32px", "26px", "22px", "18px", "16px", "14px"] +headingFontWeights = [700, 700, 600, 600, 600, 600] +linkUnderline = true +chartCategoricalColors = ["#F37626", "#2196F3", "#4CAF50", "#9C27B0", "#FF5722", "#607D8B", "#E91E63"] + +# Jupyter-inspired palette +orangeColor = "#F37626" +blueColor = "#2196F3" +greenColor = "#4CAF50" +violetColor = "#9C27B0" +redColor = "#E91E63" +yellowColor = "#FFC107" +grayColor = "#607D8B" + +dataframeBorderColor = "#E0E0E0" +dataframeHeaderBackgroundColor = "#F0F0F0" + +[theme.sidebar] +backgroundColor = "#F7F7F7" +secondaryBackgroundColor = "#EEEEEE" +codeBackgroundColor = "#E8E8E8" +textColor = "#212121" +borderColor = "#CFCFCF" +primaryColor = "#F37626" +dataframeHeaderBackgroundColor = "#EEEEEE" +dataframeBorderColor = "#CFCFCF" diff --git a/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/material-ui.toml b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/material-ui.toml new file mode 100644 index 0000000000..cf4db13100 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/material-ui.toml @@ -0,0 +1,45 @@ +# Material UI Theme for Streamlit +# Google's Material Design 3 aesthetic +# Clean, accessible, systematic design language + +[theme] +base = "light" +primaryColor = "#6750A4" +backgroundColor = "#FFFBFE" +secondaryBackgroundColor = "#F7F2FA" +codeBackgroundColor = "#E8DEF8" +textColor = "#1C1B1F" +linkColor = "#6750A4" +borderColor = "#CAC4D0" +showWidgetBorder = false +showSidebarBorder = false +baseRadius = "16px" +buttonRadius = "full" +font = "'Roboto':https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" +codeFont = "'Roboto Mono':https://fonts.googleapis.com/css2?family=Roboto+Mono:wght@400;500&display=swap" +codeFontSize = "14px" +codeTextColor = "#1C1B1F" +baseFontSize = 14 +baseFontWeight = 400 +headingFontSizes = ["36px", "28px", "22px", "18px", "16px", "14px"] +headingFontWeights = [400, 400, 500, 500, 500, 500] +linkUnderline = false +# Material Design color system +chartCategoricalColors = ["#6750A4", "#7D5260", "#625B71", "#B3261E", "#006874", "#386A20", "#924C25"] + +# Material Design 3 colors +violetColor = "#6750A4" +redColor = "#B3261E" +greenColor = "#386A20" +blueColor = "#006874" +orangeColor = "#924C25" +yellowColor = "#7C5800" + +dataframeBorderColor = "#CAC4D0" +dataframeHeaderBackgroundColor = "#E8DEF8" + +[theme.sidebar] +backgroundColor = "#F7F2FA" +secondaryBackgroundColor = "#E8DEF8" +codeBackgroundColor = "#D0BCFF" +borderColor = "#CAC4D0" diff --git a/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/minimal.toml b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/minimal.toml new file mode 100644 index 0000000000..28b4b8a034 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/minimal.toml @@ -0,0 +1,39 @@ +# Minimal Dark Theme for Streamlit +# Clean, distraction-free dark theme with subtle accents +[theme] +base = "dark" +primaryColor = "#6366f1" +backgroundColor = "#18181b" +secondaryBackgroundColor = "#27272a" +codeBackgroundColor = "#27272a" +textColor = "#fafafa" +linkColor = "#818cf8" +borderColor = "#3f3f46" +showWidgetBorder = false +showSidebarBorder = false +baseRadius = "6px" +buttonRadius = "6px" +font = "Inter:https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" +codeFont = "'JetBrains Mono':https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500&display=swap" +codeFontSize = "0.85rem" +codeTextColor = "#e4e4e7" +baseFontSize = 14 +baseFontWeight = 400 +headingFontSizes = ["32px", "24px", "20px", "16px", "14px", "12px"] +headingFontWeights = [600, 600, 500, 500, 500, 500] +linkUnderline = false +chartCategoricalColors = ["#6366f1", "#8b5cf6", "#ec4899", "#14b8a6", "#f59e0b", "#ef4444", "#22c55e"] + +# Color palette +violetColor = "#8b5cf6" +blueColor = "#6366f1" +greenColor = "#22c55e" +yellowColor = "#f59e0b" +orangeColor = "#f97316" +redColor = "#ef4444" + +[theme.sidebar] +backgroundColor = "#09090b" +secondaryBackgroundColor = "#18181b" +codeBackgroundColor = "#18181b" +borderColor = "#27272a" diff --git a/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/nord.toml b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/nord.toml new file mode 100644 index 0000000000..1b3370dc2b --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/nord.toml @@ -0,0 +1,39 @@ +# Nord Theme for Streamlit +# Arctic, north-bluish color palette with frost-inspired accents +[theme] +base = "dark" +primaryColor = "#88c0d0" +backgroundColor = "#2e3440" +secondaryBackgroundColor = "#3b4252" +codeBackgroundColor = "#3b4252" +textColor = "#eceff4" +linkColor = "#81a1c1" +borderColor = "#4c566a" +showWidgetBorder = true +showSidebarBorder = true +baseRadius = "4px" +buttonRadius = "4px" +font = "Inter:https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" +codeFont = "'JetBrains Mono':https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500&display=swap" +codeFontSize = "0.875rem" +codeTextColor = "#d8dee9" +baseFontSize = 14 +baseFontWeight = 400 +headingFontSizes = ["32px", "24px", "20px", "16px", "14px", "12px"] +headingFontWeights = [600, 600, 600, 600, 600, 600] +linkUnderline = false +chartCategoricalColors = ["#88c0d0", "#81a1c1", "#5e81ac", "#a3be8c", "#ebcb8b", "#d08770", "#bf616a"] + +# Nord color palette (Frost + Aurora) +blueColor = "#81a1c1" +greenColor = "#a3be8c" +yellowColor = "#ebcb8b" +orangeColor = "#d08770" +redColor = "#bf616a" +violetColor = "#b48ead" + +[theme.sidebar] +backgroundColor = "#3b4252" +secondaryBackgroundColor = "#434c5e" +codeBackgroundColor = "#434c5e" +borderColor = "#4c566a" diff --git a/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/one-dark-pro.toml b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/one-dark-pro.toml new file mode 100644 index 0000000000..c56cbbe316 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/one-dark-pro.toml @@ -0,0 +1,41 @@ +# One Dark Pro Theme for Streamlit +# The beloved Atom/VS Code theme with vibrant syntax colors +# Perfect balance of contrast and aesthetics + +[theme] +base = "dark" +primaryColor = "#61afef" +backgroundColor = "#282c34" +secondaryBackgroundColor = "#21252b" +codeBackgroundColor = "#1e2127" +textColor = "#abb2bf" +linkColor = "#61afef" +borderColor = "#3e4451" +showWidgetBorder = true +showSidebarBorder = true +baseRadius = "6px" +buttonRadius = "6px" +font = "'IBM Plex Sans':https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;500;600;700&display=swap" +codeFont = "'JetBrains Mono':https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500&display=swap" +codeFontSize = "13px" +codeTextColor = "#abb2bf" +baseFontSize = 14 +baseFontWeight = 400 +headingFontSizes = ["30px", "24px", "20px", "16px", "14px", "12px"] +headingFontWeights = [600, 600, 500, 500, 500, 500] +linkUnderline = false +chartCategoricalColors = ["#61afef", "#98c379", "#e5c07b", "#e06c75", "#c678dd", "#56b6c2", "#d19a66"] + +# One Dark Pro syntax colors +blueColor = "#61afef" +greenColor = "#98c379" +yellowColor = "#e5c07b" +redColor = "#e06c75" +violetColor = "#c678dd" +orangeColor = "#d19a66" + +[theme.sidebar] +backgroundColor = "#21252b" +secondaryBackgroundColor = "#282c34" +codeBackgroundColor = "#1e2127" +borderColor = "#3e4451" diff --git a/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/shadcn-dual.toml b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/shadcn-dual.toml new file mode 100644 index 0000000000..286c677c54 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/shadcn-dual.toml @@ -0,0 +1,79 @@ +# shadcn/ui-inspired dual light/dark Streamlit theme +# Use when the settings appearance toggle should stay available + +[theme] +showWidgetBorder = true +showSidebarBorder = true +baseRadius = "6px" +buttonRadius = "6px" +font = "'Inter':https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" +codeFont = "'JetBrains Mono':https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500&display=swap" +codeFontSize = "0.875rem" +baseFontSize = 14 +baseFontWeight = 400 +headingFontSizes = ["36px", "30px", "24px", "20px", "16px", "14px"] +headingFontWeights = [600, 600, 600, 600, 600, 600] +linkUnderline = true + +[theme.light] +primaryColor = "#18181B" +backgroundColor = "#FFFFFF" +secondaryBackgroundColor = "#FAFAFA" +codeBackgroundColor = "#F4F4F5" +textColor = "#09090B" +linkColor = "#18181B" +borderColor = "#E4E4E7" +codeTextColor = "#18181B" +grayColor = "#71717A" +blueColor = "#3B82F6" +greenColor = "#22C55E" +redColor = "#EF4444" +yellowColor = "#EAB308" +orangeColor = "#F97316" +violetColor = "#8B5CF6" +chartCategoricalColors = ["#18181B", "#71717A", "#A1A1AA", "#D4D4D8", "#3B82F6", "#EF4444", "#22C55E"] +dataframeBorderColor = "#E4E4E7" +dataframeHeaderBackgroundColor = "#FAFAFA" + +[theme.dark] +primaryColor = "#71717A" +backgroundColor = "#09090B" +secondaryBackgroundColor = "#18181B" +codeBackgroundColor = "#27272A" +textColor = "#FAFAFA" +linkColor = "#E4E4E7" +borderColor = "#27272A" +codeTextColor = "#E4E4E7" +grayColor = "#A1A1AA" +blueColor = "#60A5FA" +greenColor = "#4ADE80" +redColor = "#F87171" +yellowColor = "#FACC15" +orangeColor = "#FB923C" +violetColor = "#A78BFA" +chartCategoricalColors = ["#E4E4E7", "#A1A1AA", "#71717A", "#52525B", "#60A5FA", "#F87171", "#4ADE80"] +dataframeBorderColor = "#27272A" +dataframeHeaderBackgroundColor = "#18181B" +dataframeHeaderTextColor = "#FAFAFA" + +[theme.light.sidebar] +backgroundColor = "#FAFAFA" +secondaryBackgroundColor = "#F4F4F5" +codeBackgroundColor = "#E4E4E7" +textColor = "#09090B" +borderColor = "#E4E4E7" +primaryColor = "#18181B" +linkColor = "#18181B" +dataframeHeaderBackgroundColor = "#F4F4F5" +dataframeBorderColor = "#E4E4E7" + +[theme.dark.sidebar] +backgroundColor = "#000000" +secondaryBackgroundColor = "#18181B" +codeBackgroundColor = "#27272A" +textColor = "#FAFAFA" +borderColor = "#27272A" +primaryColor = "#71717A" +linkColor = "#E4E4E7" +dataframeHeaderBackgroundColor = "#18181B" +dataframeBorderColor = "#27272A" diff --git a/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/shadcn.toml b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/shadcn.toml new file mode 100644 index 0000000000..1b2e42012e --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/shadcn.toml @@ -0,0 +1,49 @@ +# shadcn/ui-inspired Streamlit Theme +# Beautifully designed components aesthetic +# Minimal, accessible, elegant with neutral palette + +[theme] +base = "light" +primaryColor = "#18181B" +backgroundColor = "#FFFFFF" +secondaryBackgroundColor = "#FAFAFA" +codeBackgroundColor = "#F4F4F5" +textColor = "#09090B" +linkColor = "#18181B" +borderColor = "#E4E4E7" +showWidgetBorder = true +showSidebarBorder = true +baseRadius = "6px" +buttonRadius = "6px" +font = "'Inter':https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" +codeFont = "'JetBrains Mono':https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500&display=swap" +codeFontSize = "0.875rem" +codeTextColor = "#18181B" +baseFontSize = 14 +baseFontWeight = 400 +headingFontSizes = ["36px", "30px", "24px", "20px", "16px", "14px"] +headingFontWeights = [600, 600, 600, 600, 600, 600] +linkUnderline = true +chartCategoricalColors = ["#18181B", "#71717A", "#A1A1AA", "#D4D4D8", "#3B82F6", "#EF4444", "#22C55E"] + +# shadcn zinc palette +grayColor = "#71717A" +blueColor = "#3B82F6" +greenColor = "#22C55E" +redColor = "#EF4444" +yellowColor = "#EAB308" +orangeColor = "#F97316" +violetColor = "#8B5CF6" + +dataframeBorderColor = "#E4E4E7" +dataframeHeaderBackgroundColor = "#FAFAFA" + +[theme.sidebar] +backgroundColor = "#FAFAFA" +secondaryBackgroundColor = "#F4F4F5" +codeBackgroundColor = "#E4E4E7" +textColor = "#09090B" +borderColor = "#E4E4E7" +primaryColor = "#18181B" +dataframeHeaderBackgroundColor = "#F4F4F5" +dataframeBorderColor = "#E4E4E7" diff --git a/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/solarized-light.toml b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/solarized-light.toml new file mode 100644 index 0000000000..8954d12396 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/solarized-light.toml @@ -0,0 +1,39 @@ +# Solarized Light Theme for Streamlit +# Precision colors designed for readability and reduced eye strain +[theme] +base = "light" +primaryColor = "#268bd2" +backgroundColor = "#fdf6e3" +secondaryBackgroundColor = "#eee8d5" +codeBackgroundColor = "#eee8d5" +textColor = "#657b83" +linkColor = "#268bd2" +borderColor = "#93a1a1" +showWidgetBorder = true +showSidebarBorder = true +baseRadius = "4px" +buttonRadius = "4px" +font = "'Source Sans 3':https://fonts.googleapis.com/css2?family=Source+Sans+3:wght@400;500;600;700&display=swap" +codeFont = "'Source Code Pro':https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght@400;500&display=swap" +codeFontSize = "0.875rem" +codeTextColor = "#586e75" +baseFontSize = 14 +baseFontWeight = 400 +headingFontSizes = ["32px", "24px", "20px", "16px", "14px", "12px"] +headingFontWeights = [600, 600, 600, 600, 600, 600] +linkUnderline = false +chartCategoricalColors = ["#268bd2", "#2aa198", "#859900", "#b58900", "#cb4b16", "#dc322f", "#d33682"] + +# Solarized color palette +blueColor = "#268bd2" +greenColor = "#859900" +yellowColor = "#b58900" +orangeColor = "#cb4b16" +redColor = "#dc322f" +violetColor = "#6c71c4" + +[theme.sidebar] +backgroundColor = "#eee8d5" +secondaryBackgroundColor = "#fdf6e3" +codeBackgroundColor = "#fdf6e3" +borderColor = "#93a1a1" diff --git a/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/ubuntu.toml b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/ubuntu.toml new file mode 100644 index 0000000000..57552700c1 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/ubuntu.toml @@ -0,0 +1,50 @@ +# Ubuntu-inspired Streamlit Theme +# Linux for human beings aesthetic +# Warm orange, friendly purple, open source spirit + +[theme] +base = "light" +primaryColor = "#E95420" +backgroundColor = "#FFFFFF" +secondaryBackgroundColor = "#F7F7F7" +codeBackgroundColor = "#F0F0F0" +textColor = "#111111" +linkColor = "#E95420" +borderColor = "#CDCDCD" +showWidgetBorder = true +showSidebarBorder = true +baseRadius = "6px" +buttonRadius = "4px" +font = "'Ubuntu':https://fonts.googleapis.com/css2?family=Ubuntu:wght@300;400;500;700&display=swap" +codeFont = "'Ubuntu Mono':https://fonts.googleapis.com/css2?family=Ubuntu+Mono:wght@400;700&display=swap" +codeFontSize = "0.9rem" +codeTextColor = "#111111" +baseFontSize = 15 +baseFontWeight = 400 +headingFontSizes = ["32px", "26px", "22px", "18px", "16px", "14px"] +headingFontWeights = [500, 500, 500, 500, 500, 500] +linkUnderline = false +chartCategoricalColors = ["#E95420", "#772953", "#77216F", "#5E2750", "#2C001E", "#AEA79F", "#333333"] + +# Ubuntu color palette +orangeColor = "#E95420" +violetColor = "#772953" +redColor = "#DF382C" +greenColor = "#38B44A" +blueColor = "#19B6EE" +yellowColor = "#EFB73E" +grayColor = "#AEA79F" + +dataframeBorderColor = "#CDCDCD" +dataframeHeaderBackgroundColor = "#F0F0F0" + +[theme.sidebar] +backgroundColor = "#2C001E" +secondaryBackgroundColor = "#3D0028" +codeBackgroundColor = "#1A0012" +textColor = "#FFFFFF" +borderColor = "#5E2750" +primaryColor = "#E95420" +dataframeHeaderBackgroundColor = "#3D0028" +dataframeHeaderTextColor = "#FFFFFF" +dataframeBorderColor = "#5E2750" diff --git a/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/vscode.toml b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/vscode.toml new file mode 100644 index 0000000000..6d76f67af1 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/assets/templates/themes/configs/vscode.toml @@ -0,0 +1,40 @@ +# VS Code Dark Theme for Streamlit +# The classic Visual Studio Code default dark theme +# Developer-friendly, easy on the eyes + +[theme] +base = "dark" +primaryColor = "#0078d4" +backgroundColor = "#1e1e1e" +secondaryBackgroundColor = "#252526" +codeBackgroundColor = "#1e1e1e" +textColor = "#cccccc" +linkColor = "#3794ff" +borderColor = "#3c3c3c" +showWidgetBorder = true +showSidebarBorder = true +baseRadius = "4px" +buttonRadius = "4px" +font = "'Segoe UI', 'Open Sans':https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;500;600;700&display=swap" +codeFont = "'Fira Code':https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;500&display=swap" +codeFontSize = "13px" +codeTextColor = "#d4d4d4" +baseFontSize = 14 +baseFontWeight = 400 +headingFontSizes = ["28px", "22px", "18px", "16px", "14px", "12px"] +headingFontWeights = [600, 600, 600, 600, 600, 600] +linkUnderline = false +chartCategoricalColors = ["#0078d4", "#4ec9b0", "#dcdcaa", "#ce9178", "#c586c0", "#569cd6", "#6a9955"] + +# VS Code syntax colors +blueColor = "#569cd6" +greenColor = "#6a9955" +yellowColor = "#dcdcaa" +orangeColor = "#ce9178" +violetColor = "#c586c0" + +[theme.sidebar] +backgroundColor = "#252526" +secondaryBackgroundColor = "#333333" +codeBackgroundColor = "#1e1e1e" +borderColor = "#3c3c3c" diff --git a/.agents/skills/developing-with-streamlit/references/api-reference.md b/.agents/skills/developing-with-streamlit/references/api-reference.md new file mode 100644 index 0000000000..91a672d074 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/references/api-reference.md @@ -0,0 +1,194 @@ +# Streamlit API reference + +Use this as a quick orientation for the public top-level `st` API. The table below covers the public `st.(...)` commands, common top-level objects, `st.column_config` helpers, and public namespaces exposed by the local Streamlit namespace when this reference was written. + +Treat summaries as starting points, not complete usage docs. Before using unfamiliar parameters, deprecated options, return values, or command-specific edge cases, inspect the local docstring and signature. + +## Inspecting local docs from the CLI + +Use `streamlit docs ` to print the signature and docstring for a public Streamlit command from the relevant Streamlit installation: + +```bash +streamlit docs st.button +``` + +It also supports public nested namespace members: + +```bash +streamlit docs st.column_config.NumberColumn +streamlit docs st.cache_data.clear +``` + +For container usage, look up the same top-level command because container methods share the same public element docs: + +```bash +streamlit docs st.button +# Applies to st.button(...), st.sidebar.button(...), and buttons in other containers. +``` + +Run this command with the Streamlit installation relevant to the code being edited. For example, use the active virtual environment, the project's package runner, or the repo's development environment so the docs match that Streamlit version. If `COMMAND` is omitted, `streamlit docs` opens the documentation website in a browser instead of printing command docs. + +## Public `st` API + +| API | Summary | +|-----|---------| +| **Top-level commands** | | +| `st.App` | ASGI-compatible Streamlit application. Use it for advanced server configuration, including custom routes, startup and shutdown lifecycle hooks, custom middleware, custom exception handlers, FastAPI integration, and programmatic secrets. | +| `st.Page` | Configure a page for `st.navigation` in a multipage app. It creates a page object from a Python file or callable with optional title, icon, URL path, default status, and visibility. | +| `st.altair_chart` | Display a chart using the Vega-Altair library. Use it when native charts are not expressive enough and you need Altair's encodings, layers, tooltips, or interactions. | +| `st.area_chart` | Display an area chart. Use it for common area-chart cases with Streamlit-managed rendering. | +| `st.audio` | Display an audio player. Accepts common audio data sources such as files, URLs, bytes, and arrays. | +| `st.audio_input` | Display a widget that returns an audio recording from the user's microphone. Use it when an app needs recorded audio as input. | +| `st.badge` | Display a colored badge with an icon and label. Useful for compact status, category, or metadata indicators. | +| `st.balloons` | Draw celebratory balloons. Use sparingly for success moments or lightweight feedback. | +| `st.bar_chart` | Display a bar chart. Use it for straightforward categorical or binned comparisons. | +| `st.button` | Display a button widget. It returns `True` on the script rerun triggered by a click. | +| `st.cache_data` | Cache the return value of a function. Use it for expensive computations or data-loading steps that return serializable data; each caller receives a copy of the cached value. | +| `st.cache_resource` | Cache a shared resource returned by a function. Use it for global objects such as database connections, ML models, or clients that should be reused across reruns and sessions. | +| `st.camera_input` | Display a widget that returns pictures from the user's webcam. It returns an `UploadedFile` with the captured image when the user takes a picture, and `None` before then. | +| `st.caption` | Display text in small font. Use it for secondary text, notes, or metadata beneath primary content. | +| `st.chat_input` | Display a chat input widget. It is designed for conversational apps and returns the submitted message or uploaded files depending on configuration. | +| `st.chat_message` | Insert a chat message container. Use it to render messages from users, assistants, or named speakers. | +| `st.checkbox` | Display a checkbox widget. It returns a boolean value. | +| `st.code` | Display a code block with optional syntax highlighting. Use it for source code, commands, logs, and other preformatted text. | +| `st.color_picker` | Display a color picker widget. It returns the selected color as a hex string. | +| `st.columns` | Insert containers laid out as side-by-side columns. Use it for horizontal layouts and place elements into returned column containers. | +| `st.connection` | Create or retrieve a connection to a data store or API. Use connection classes and secrets to centralize external service access. | +| `st.container` | Insert a multi-element container. Use it to group elements, control layout, or append content to a specific location. | +| `st.data_editor` | Display a data editor widget. Use it when users need to edit rows or cells and the app needs the edited data back in Python. | +| `st.dataframe` | Display a dataframe as an interactive table. Supports column configuration, selection, sizing, sorting, and efficient data exploration. | +| `st.date_input` | Display a date input widget. It can return a single date or a date range depending on the initial value. | +| `st.datetime_input` | Display a date and time input widget. Use it when users need to choose precise timestamps rather than dates alone. | +| `st.dialog` | Function decorator to create a modal dialog or a modal side drawer. Use it to isolate short workflows while preserving Streamlit's rerun model. | +| `st.divider` | Display a horizontal rule. Use it to separate sections without adding a heavy layout container. | +| `st.download_button` | Display a download button widget. Use it for generated files, reports, transformed data, or other app outputs. | +| `st.echarts_chart` | Display an interactive Apache ECharts chart. Use it for ECharts-native visualizations. | +| `st.echo` | Use in a `with` block to draw some code on the app, then execute it. Useful for tutorials, examples, and educational apps. | +| `st.empty` | Insert a single-element container. Use it as a placeholder when you need to replace, update, or clear one element later. | +| `st.error` | Display error message. Use it for failures or blocking conditions that require user attention. | +| `st.exception` | Display an exception. Use it to surface caught exceptions and traceback information during debugging or diagnostics. | +| `st.expander` | Insert a multi-element container that can be expanded/collapsed. Use it for optional details that should not dominate the main page. | +| `st.feedback` | Display a feedback widget. It supports compact user reactions such as thumbs, faces, or stars depending on configuration. | +| `st.file_uploader` | Display a file uploader widget. It returns uploaded file objects and can support multiple files and type filtering. | +| `st.form` | Create a form that batches elements together with a "Submit" button. Use it when several inputs should update the app together instead of on every widget change. Every form must contain at least one `st.form_submit_button`, otherwise it's non-functional. | +| `st.form_submit_button` | Display a form submit button. It must be used inside `st.form` and triggers the form's batched submission. A form needs at least one submit button to be functional. | +| `st.fragment` | Decorator to turn a function into a fragment which can rerun independently of the full app. Use it to reduce rerun cost for isolated interactive sections or run independent, slow sections in parallel during full app reruns. | +| `st.get_option` | Return the current value of a given Streamlit configuration option. Use it for runtime-aware behavior that depends on configured settings. | +| `st.graphviz_chart` | Display a graph using the d3-graphviz library and Graphviz WASM. Use it for directed graphs, diagrams, and node-edge visualizations. | +| `st.header` | Display text in header formatting. Use it for major sections below the page title. | +| `st.help` | Display help and other information for a given object. It renders docstrings, signatures, and related information inside the app. | +| `st.html` | Insert HTML into your app. JavaScript is ignored by default; for interactive components that exchange data with Python, use `st.components.v2.component()` instead. | +| `st.iframe` | Embed content in an iframe. Use it to show an external page or embedded resource in a bounded frame. | +| `st.image` | Display an image or list of images. Accepts paths, URLs, bytes, arrays, and image-like objects. | +| `st.info` | Display an informational message. Use it for neutral guidance, context, or non-blocking status. | +| `st.json` | Display an object or string as a pretty-printed, interactive JSON string. Use it for structured debug output or data inspection. | +| `st.latex` | Display mathematical expressions formatted as LaTeX. Use it for equations and scientific notation. | +| `st.line_chart` | Display a line chart. Use it for trends, time series, and ordered numeric values. | +| `st.link_button` | Display a link button element. Use it when the action is navigation to another URL. | +| `st.login` | Initiate the login flow for the given provider. Use it with configured auth settings and inspect the local docs for provider-specific behavior. | +| `st.logo` | Renders a logo in the upper-left corner of your app and its sidebar. Use it for app branding and optional navigation link behavior. | +| `st.logout` | Logout the current user. Use it with Streamlit's authentication support. | +| `st.map` | Display a map with a scatterplot overlaid onto it. Use it for latitude/longitude data when a simple geographic visualization is enough. | +| `st.markdown` | Display string formatted as Markdown. It supports Streamlit-specific extensions such as colored text, badges, icons, and limited HTML when enabled. | +| `st.menu_button` | Display a button that opens a short menu of one-shot actions. Like `st.button`, it returns the chosen option only on the rerun the click triggers. | +| `st.mermaid_chart` | Display a Mermaid diagram. Use it for text-based diagram definitions such as flowcharts, sequence diagrams, class diagrams, and state diagrams. | +| `st.metric` | Display a metric in big bold font, with an optional indicator of how the metric changed. Use it for KPIs, headline numbers, optional inline sparklines, and dashboard summaries. | +| `st.multiselect` | Display a multiselect widget. Use it when users can choose multiple items from a list, optionally including new options they enter. | +| `st.navigation` | Configure the available pages in a multipage app and where the navigation menu appears. It returns the currently selected page object, which the app should run. | +| `st.number_input` | Display a numeric input widget. It supports integer and floating-point values, bounds, steps, and formatting. | +| `st.page_link` | Display a link to another page in a multipage app or to an external page. Use it for explicit navigation elements. | +| `st.pagination` | Display a pagination widget for navigating through pages of content. Use it when a dataset or workflow is split across numbered pages. | +| `st.pdf` | Display a PDF viewer. Use it to render PDF files or bytes directly in the app. | +| `st.pills` | Display a pills widget. Use it for compact single- or multi-select choices with pill-shaped options. | +| `st.plotly_chart` | Display an interactive Plotly chart. Use it when Plotly is already available or chart interactions/customization require Plotly. | +| `st.popover` | Insert a popover container. Use it for compact controls or details that should appear on demand without occupying page space. | +| `st.progress` | Display a progress bar. Use it to communicate completion state for running tasks or staged workflows. | +| `st.pydeck_chart` | Draw a chart using the PyDeck library. Use it for deck.gl-powered maps and geospatial visualizations. | +| `st.pyplot` | Display a matplotlib.pyplot figure. Use it for existing Matplotlib visualizations or libraries that produce Matplotlib figures. | +| `st.radio` | Display a radio button widget. Use it when users should choose exactly one option from a small visible set. | +| `st.rerun` | Rerun the app or current fragment immediately. Use it to force a rerun after state changes or navigation-like actions. | +| `st.scatter_chart` | Display a scatterplot chart. Use it for relationships between numeric variables, optionally with size and color encodings. | +| `st.segmented_control` | Display a segmented control widget. Use it for compact mutually exclusive choices, especially mode or view switching. | +| `st.select_slider` | Display a slider widget to select items from a list. Use it when options are ordered but not necessarily numeric. | +| `st.selectbox` | Display a select widget. Use it for selecting one item from a medium or large set. | +| `st.set_option` | Set a configuration option. Use sparingly because not all options are safe or meaningful to change after startup. | +| `st.set_page_config` | Configure the default settings of the page. Prefer calling it near the top of the script; repeated calls are additive and override only the parameters you specify. | +| `st.skeleton` | Display a skeleton loading placeholder. Use it standalone (like `st.empty`) to reserve space and replace it with content later, or as a context manager (like `st.spinner`) to show a temporary placeholder while a block runs. | +| `st.slider` | Display a slider widget. Use it for numeric ranges, dates, times, or other ordered values. | +| `st.snow` | Draw celebratory snowfall. Use sparingly for lightweight success or celebration effects. | +| `st.space` | Add vertical or horizontal space. Use it for small layout adjustments instead of empty Markdown strings. | +| `st.spinner` | Display a loading spinner while executing a block of code. Use it as a context manager around work that may take noticeable time. | +| `st.status` | Insert a status container to display output from long-running tasks. Use it to show progress, intermediate output, and final state for multi-step operations. | +| `st.stop` | Stops execution immediately. Use it to halt rendering after validation failures, missing inputs, or intentional early exits. | +| `st.subheader` | Display text in subheader formatting. Use it for subsections under headers. | +| `st.success` | Display a success message. Use it for completed actions or positive status. | +| `st.switch_page` | Programmatically switch the current page in a multipage app. Use it for navigation triggered by app logic. | +| `st.table` | Display data in a static table. Use it for small, styled tables such as key-value summaries, confusion matrices, or leaderboards, including cells with supported Markdown, when users do not need interactive exploration. | +| `st.tabs` | Insert containers separated into tabs. Use tabs to switch between related views while rendering all tab content in the same run. | +| `st.text` | Write text without Markdown or HTML parsing. Use it for unformatted output. | +| `st.text_area` | Display a multi-line text input widget. Use it for comments, prompts, notes, and longer free-form input. | +| `st.text_input` | Display a single-line text input widget. Use it for short free-form input such as names, filters, IDs, or search text. | +| `st.time_input` | Display a time input widget. Use it when users need to choose a time of day. | +| `st.title` | Display text in title formatting. Use it for the main page title. | +| `st.toast` | Display a short message, known as a notification "toast". It appears in the app's top-right corner and disappears after four seconds. | +| `st.toggle` | Display a toggle widget. Use it for boolean settings that behave like on/off switches. | +| `st.vega_lite_chart` | Display a chart using the Vega-Lite library. Use it for direct Vega-Lite specifications or when you already have Vega-Lite JSON. | +| `st.video` | Display a video player. Accepts common video data sources such as files, URLs, bytes, and arrays. | +| `st.warning` | Display warning message. Use it for cautionary or recoverable conditions that need attention. | +| `st.write` | Displays arguments in the app. Use it for quick output, mixed content, and exploratory apps. | +| `st.write_stream` | Stream a generator, iterable, or stream-like sequence to the app. Use it for token streams, incremental text, or progressively produced output. | +| **Top-level objects** | | +| `st.bottom` | Bottom-pinned container for the main app area. Use it as a container object, not as a function. | +| `st.context` | Read-only access to user session context. Exposes `headers`, `cookies`, `theme` (`theme.type`), `timezone`, `timezone_offset`, `locale`, `url`, `ip_address`, and `is_embedded`. Attribute and bracket access are equivalent (`st.context.timezone` and `st.context["timezone"]`), but it is not a dict: no `.get()`, `.keys()`, or iteration. | +| `st.query_params` | Mutable mapping for the browser URL query parameters. Use it to read or update URL state; to sync a widget's value to the URL, bind the widget to query params instead. | +| `st.secrets` | Dict-like access to secrets loaded from `secrets.toml`. Use it for credentials and configuration that should not be hard-coded. | +| `st.session_state` | Per-session mutable mapping for app state. Use it to persist values across reruns and share state between widgets and app logic. | +| `st.sidebar` | Sidebar container that exposes most element methods as `st.sidebar.()` and supports `with st.sidebar:` blocks. | +| `st.user` | Read-only dict-like object for current user information. Values depend on the hosting and authentication configuration. | +| **`st.column_config` helpers** | | +| `st.column_config.AreaChartColumn` | Configure an area chart column in `st.dataframe` or `st.data_editor`. Use it for compact per-row trends where filled areas are clearer than plain numbers. | +| `st.column_config.AudioColumn` | Configure an audio column in `st.dataframe` or `st.data_editor`. Use it for audio URLs, paths, or media values that users should be able to play inline. | +| `st.column_config.BarChartColumn` | Configure a bar chart column in `st.dataframe` or `st.data_editor`. Use it for compact per-row comparisons or small sequences of numeric values. | +| `st.column_config.ButtonColumn` | Configure a button column in `st.dataframe` or `st.data_editor`. Use it when each row needs an action trigger. | +| `st.column_config.CheckboxColumn` | Configure a checkbox column in `st.dataframe` or `st.data_editor`. Use it for boolean values, especially editable true/false fields. | +| `st.column_config.Column` | Configure a generic column in `st.dataframe` or `st.data_editor`. Use it for label, width, help text, visibility, disabled state, pinned state, and other shared column metadata. | +| `st.column_config.DateColumn` | Configure a date column in `st.dataframe` or `st.data_editor`. Use it for date-only display or editing with optional formatting and bounds. | +| `st.column_config.DatetimeColumn` | Configure a datetime column in `st.dataframe` or `st.data_editor`. Use it for timestamp display or editing with optional formatting, timezone-aware values, and bounds. | +| `st.column_config.ImageColumn` | Configure an image column in `st.dataframe` or `st.data_editor`. Use it for image URLs, paths, or image-like values that should display visually instead of as text. | +| `st.column_config.JsonColumn` | Configure a JSON column in `st.dataframe` or `st.data_editor`. Use it for dictionaries, lists, or JSON strings that need structured display. | +| `st.column_config.LineChartColumn` | Configure a line chart column in `st.dataframe` or `st.data_editor`. Use it for compact per-row trends without the filled area of an area chart. | +| `st.column_config.LinkColumn` | Configure a link column in `st.dataframe` or `st.data_editor`. Use it for URLs, optionally with validation and display text behavior. | +| `st.column_config.ListColumn` | Configure a list column in `st.dataframe` or `st.data_editor`. Use it for arrays or repeated values that should render as structured list content. | +| `st.column_config.MarkdownColumn` | Configure a markdown column in `st.dataframe` or `st.data_editor`. Cells show plain text, and clicking a cell opens an overlay that renders the Markdown. | +| `st.column_config.MultiselectColumn` | Configure a multiselect column in `st.dataframe` or `st.data_editor`. Use it when each row can contain multiple choices from a known set. | +| `st.column_config.NumberColumn` | Configure a number column in `st.dataframe` or `st.data_editor`. Use it for integers, floats, currencies, percentages, min/max bounds, step sizes, and numeric formatting. | +| `st.column_config.ProgressColumn` | Configure a progress column in `st.dataframe` or `st.data_editor`. Use it for percentages, completion values, scores, or bounded progress-like quantities. | +| `st.column_config.SelectboxColumn` | Configure a selectbox column in `st.dataframe` or `st.data_editor`. Use it when each row should choose exactly one option from a known set. | +| `st.column_config.TextColumn` | Configure a text column in `st.dataframe` or `st.data_editor`. Use it for strings with optional validation, length bounds, and text-specific display or editing behavior. | +| `st.column_config.TimeColumn` | Configure a time column in `st.dataframe` or `st.data_editor`. Use it for time-of-day display or editing with optional formatting and bounds. | +| `st.column_config.VideoColumn` | Configure a video column in `st.dataframe` or `st.data_editor`. Use it for video URLs, paths, or media values that users should be able to play inline. | +| **Public namespaces** | | +| `st.column_config` | Namespace of column configuration helpers for `st.dataframe` and `st.data_editor`. See the `st.column_config` helper rows above and inspect helpers such as `st.column_config.NumberColumn` for exact parameters. | +| `st.components` | Namespace for custom components. Prefer `st.components.v2.component()` for new HTML/JS components; `st.components.v1` is deprecated for new work. | +| `st.typing` | Curated namespace of public Streamlit-owned types for annotations. Prefer imports from `streamlit.typing` over internal implementation modules. | + +## Public annotation types + +Import Streamlit-owned return and state types from `streamlit.typing`, not from modules under `streamlit.elements` or `streamlit.runtime`: + +```python +from streamlit.typing import DataframeState, UploadedFile +``` + +| Type | Produced by | +|------|-------------| +| `UploadedFile` | `st.file_uploader`, `st.camera_input`, `st.audio_input`, and file/audio fields from `st.chat_input` | +| `ChatInputValue` | `st.chat_input` when file or audio input is enabled | +| `DataframeState` | `st.dataframe` when selection events are enabled | +| `PlotlyState` | `st.plotly_chart` when selection events are enabled | +| `VegaLiteState` | `st.altair_chart` and `st.vega_lite_chart` when selection events are enabled | +| `PydeckState` | `st.pydeck_chart` when selection events are enabled | +| `DataEditorState` | Session State for a keyed `st.data_editor` | +| `ButtonColumnClickState` | Session State for a keyed `st.column_config.ButtonColumn` click | + +These are the runtime classes returned by Streamlit, so they work in annotations and `isinstance` checks. Obtain their values from the corresponding command or Session State entry instead of constructing them directly. diff --git a/.agents/skills/developing-with-streamlit/references/authentication.md b/.agents/skills/developing-with-streamlit/references/authentication.md new file mode 100644 index 0000000000..d0eb1d271e --- /dev/null +++ b/.agents/skills/developing-with-streamlit/references/authentication.md @@ -0,0 +1,159 @@ + +# Streamlit user authentication + +Add real user sign-in with `st.login`, `st.logout`, and `st.user`. + +## Don't roll your own password gate + +A `st.text_input(type="password")` compared against a hardcoded string (or a +secret) is not authentication. It has no concept of user identity, the +"password" is shared by everyone, and the gate is trivially bypassed. Use +`st.login()` with a real OpenID Connect (OIDC) identity provider instead. + +```python +# BAD — a fake gate, not authentication +import streamlit as st + +if st.text_input("Password", type="password") != "hunter2": + st.stop() +st.write("Secret dashboard") +``` + +```python +# GOOD — real OIDC identity via st.login +import streamlit as st + +if not st.user.is_logged_in: + st.login() + st.stop() + +st.write(f"Hello, {st.user.name}!") +if st.button("Log out"): + st.logout() +``` + +**Why st.login:** +- Real per-user identity from a trusted provider (Google, Microsoft, Okta, Auth0, …) +- Signed identity cookie — can't be faked client-side +- Configuring `[auth]` turns on XSRF protection automatically +- `st.user` exposes verified claims (email, name, etc.); no password handling in your code + +## Requirements + +The auth flow needs the optional `auth` extra, which pulls in Authlib: + +```shell +pip install "streamlit[auth]" +``` + +This is app-level authentication. It is unrelated to `st.text_input(type="password")`, +which is just a masked text field with no identity behind it. + +## Configure the provider in secrets.toml + +All auth config lives in an `[auth]` section of `.streamlit/secrets.toml`. +`redirect_uri` and `cookie_secret` are shared across every provider, along with +the optional `expose_tokens`. Each provider needs its own `client_id`, +`client_secret`, and `server_metadata_url`. + +```toml +# .streamlit/secrets.toml +[auth] +redirect_uri = "http://localhost:8501/oauth2callback" +cookie_secret = "a-strong-randomly-generated-secret" +client_id = "xxx" +client_secret = "xxx" +server_metadata_url = "https://accounts.google.com/.well-known/openid-configuration" +``` + +- `redirect_uri` must be your app's absolute URL ending in `/oauth2callback`. For + local dev on the default port that's `http://localhost:8501/oauth2callback`. + Update it (in both secrets and your provider) when you deploy. +- `cookie_secret` signs the identity cookie. Use a long, random value. +- `client_id`, `client_secret`, and `server_metadata_url` come from your OIDC + provider's app registration. + +Never commit this file. Add it to `.gitignore`: + +``` +.streamlit/secrets.toml +``` + +## Gate the whole app + +The canonical pattern: bail out early when the user isn't signed in, then render +protected content. + +```python +import streamlit as st + +if not st.user.is_logged_in: + st.title("Please log in") + if st.button("Log in with Google"): + st.login() + st.stop() + +# Everything below only runs for authenticated users +st.title("Dashboard") +st.write(f"Signed in as {st.user.name} ({st.user.email})") + +with st.sidebar: + if st.button("Log out"): + st.logout() +``` + +`st.user.is_logged_in` is `True` only after a successful `st.login()`. +`st.user.email`, `st.user.name`, and other fields are claims parsed from the +provider's identity token (available claims vary by provider). `st.logout()` +clears the identity cookie and starts a fresh session. + +## Multiple named providers + +Give users a choice of identity providers by adding `[auth.]` sections. +Keep `redirect_uri` and `cookie_secret` in the shared `[auth]` section, and put +each provider's credentials in its own section. The name is internal to your app +and is passed to `st.login("")`. + +```toml +# .streamlit/secrets.toml +[auth] +redirect_uri = "http://localhost:8501/oauth2callback" +cookie_secret = "a-strong-randomly-generated-secret" + +[auth.google] +client_id = "xxx" +client_secret = "xxx" +server_metadata_url = "https://accounts.google.com/.well-known/openid-configuration" + +[auth.microsoft] +client_id = "xxx" +client_secret = "xxx" +server_metadata_url = "https://login.microsoftonline.com/{tenant}/v2.0/.well-known/openid-configuration" +``` + +```python +import streamlit as st + +if not st.user.is_logged_in: + st.header("Log in:") + if st.button("Google"): + st.login("google") + if st.button("Microsoft"): + st.login("microsoft") + st.stop() + +st.write(f"Hello, {st.user.name}!") +if st.button("Log out"): + st.logout() +``` + +Provider names can't contain underscores. Only OIDC providers are supported — +generic OAuth 2.0 providers won't work. + +## References + +- [st.login](https://docs.streamlit.io/develop/api-reference/user/st.login) +- [st.logout](https://docs.streamlit.io/develop/api-reference/user/st.logout) +- [st.user](https://docs.streamlit.io/develop/api-reference/user/st.user) +- [User authentication and information](https://docs.streamlit.io/develop/concepts/connections/authentication) +- [st.secrets](https://docs.streamlit.io/develop/api-reference/connections/st.secrets) diff --git a/.agents/skills/developing-with-streamlit/references/best-practices.md b/.agents/skills/developing-with-streamlit/references/best-practices.md new file mode 100644 index 0000000000..1fe8cff65f --- /dev/null +++ b/.agents/skills/developing-with-streamlit/references/best-practices.md @@ -0,0 +1,416 @@ +# Streamlit best practices + +Opinionated examples for writing clean, performant, and maintainable Streamlit apps. + +Use this reference when reviewing an app, starting a new app, or applying the quick-reference rules from `SKILL.md`. + +## Contents + +- [Styling and copy](#styling-and-copy) +- [HTML and iframes](#html-and-iframes) +- [Layout](#layout) +- [Navigation and pages](#navigation-and-pages) +- [Performance](#performance) +- [Data and charts](#data-and-charts) +- [Widgets and state](#widgets-and-state) +- [Secrets and queries](#secrets-and-queries) + +## Styling and copy + +Do not use custom CSS for app styling unless the user actively requests it. Prefer native Streamlit APIs and `.streamlit/config.toml` to customize the appearance. + +```python +# BAD: Styling the app with injected CSS +st.markdown( + "", + unsafe_allow_html=True, +) +``` + +```toml +# GOOD: Configure theme tokens in .streamlit/config.toml +[theme] +primaryColor = "#ff4b4b" +backgroundColor = "#ffffff" +secondaryBackgroundColor = "#f6f8fa" +textColor = "#262730" +``` + +Prefer Material Symbols icons over emojis in UI labels, and use sentence casing. + +```python +# BAD: Title casing and emoji-heavy UI +st.button("Sales Reports 📊") +st.button("Refresh Data 🔄") + +# GOOD: Sentence casing and Material Symbols +st.button("Sales reports", icon=":material/bar_chart:") +st.button("Refresh data", icon=":material/refresh:") +``` + +Do not use empty widget labels. Hide labels when the surrounding UI already provides context. + +```python +# BAD: Empty label hurts accessibility +query = st.text_input("", placeholder="Search") + +# GOOD: Accessible label, visually collapsed +query = st.text_input( + "Search", + type="search", + placeholder="Search", + label_visibility="collapsed", +) +``` + +Pass keyword-only `alt=` on images, charts, maps, media, iframes, PDFs, tables, dataframes, and data editors so assistive technologies can name them. Keep it short and specific; see [media-display.md](media-display.md) and [data-display.md](data-display.md). + +```python +# BAD: Meaningful image with no alt +st.image("revenue.png", caption="Q3 revenue") + +# GOOD: Short accessible name, independent of caption +st.image( + "revenue.png", + caption="Q3 revenue", + alt="Bar chart of monthly Q3 revenue rising to $1.2M in September", +) +``` + +## HTML and iframes + +Prefer native Streamlit elements over recreating UI with custom HTML. This includes UI created with `st.html`, `st.markdown(..., unsafe_allow_html=True)`, or deprecated `st.components.v1.html`. Use custom HTML only when no native element provides the required UI or behavior. + +Do not use the deprecated `st.components.v1.html` or `st.components.v1.iframe` commands. + +- Use `st.iframe` for URLs or HTML that should render inside an iframe. It is the iframe-based replacement for either legacy command. Pass `alt=` to set the iframe `title`. The default is a shared `"st.iframe"` name on every embed. +- Use `st.html` for static HTML or CSS that should render directly in the app instead of inside an iframe. JavaScript is ignored by default; only enable it with `unsafe_allow_javascript=True` when necessary, and never enable it for untrusted content. + +## Layout + +Use `width` instead of deprecated `use_container_width`. Dataframes and most charts stretch by default; buttons default to `width="content"`. + +```python +# BAD: Deprecated +st.dataframe(df, use_container_width=True) +st.download_button("Download CSV", df.to_csv(), "orders.csv", use_container_width=True) + +# GOOD: Dataframes stretch by default; set content width only when needed +st.dataframe(df) +st.dataframe(df, width="content") + +# GOOD: Buttons fit their content by default; stretch them explicitly +st.download_button("Download CSV", df.to_csv(), "orders.csv", width="stretch") +``` + +Prefer horizontal containers for responsive rows, and reserve columns for fixed grids, specific width ratios, or cards that must share a width. + +```python +# BAD: Columns for a simple button row +left, right = st.columns(2) +left.button("Cancel") +right.button("Save", type="primary") + +# GOOD: Responsive horizontal row +with st.container(horizontal=True, horizontal_alignment="right"): + st.button("Cancel") + st.button("Save", type="primary") +``` + +Align elements placed side by side. Bottom-align rows that mix labeled inputs with buttons, checkboxes, or toggles, and give sibling cards consistent content or `height="stretch"`. See "Aligning elements side by side" in [layouts.md](layouts.md) for element sizes and more patterns. + +```python +# BAD: The button and toggle sit above the input field; the cards have uneven heights +with st.container(horizontal=True): + st.text_input("Customer") + st.toggle("Active only") + st.button("Search") + +revenue_col, orders_col = st.columns(2) +revenue_col.metric("Revenue", "$1.2M", "+8%", border=True) +orders_col.metric("Orders", "1.4k", border=True) + +# GOOD: Everything lines up with the input field, and the cards share a height +with st.container(horizontal=True, vertical_alignment="bottom"): + st.text_input("Customer") + st.toggle("Active only") + st.button("Search") + +revenue_col, orders_col = st.columns(2) +revenue_col.metric("Revenue", "$1.2M", "+8%", border=True, height="stretch") +orders_col.metric("Orders", "1.4k", border=True, height="stretch") +``` + +Use bordered containers for visual grouping. + +```python +with st.container(border=True): + st.metric("Revenue", "$1.2M", delta="8%") + st.caption("Last 30 days") +``` + +## Navigation and pages + +Use `st.navigation` with an `app_pages/` directory. Give every `st.Page` a context-appropriate Material Symbols icon. Avoid the legacy `pages/` auto-discovery pattern and app-body navigation built from `st.page_link`. + +```python +# GOOD: streamlit_app.py +import streamlit as st + +page = st.navigation( + [ + st.Page("app_pages/home.py", title="Home", icon=":material/home:"), + st.Page("app_pages/sales.py", title="Sales", icon=":material/analytics:"), + ] +) + +page.run() +``` + +Keep page files as direct scripts. Do not wrap the page body in a render function. + +```python +# BAD: app_pages/sales.py +def render_page(): + st.title("Sales") + st.line_chart(load_sales()) + + +render_page() +``` + +```python +# GOOD: app_pages/sales.py +import streamlit as st + +from utils.data import load_sales + +st.title("Sales") +st.line_chart(load_sales(), alt="Sales over time") +``` + +## Performance + +Cache expensive work at the right granularity. Cache source data or expensive computation, then apply cheap interactive filters outside the cached function. + +```python +# BAD: Unbounded cache with one entry per filter value +@st.cache_data +def load_filtered_orders(region: str) -> pd.DataFrame: + orders = fetch_orders() + return orders[orders["region"] == region] + + +region = st.selectbox("Region", regions) +orders = load_filtered_orders(region) +``` + +```python +# GOOD: Cache the expensive source load with a practical bound +@st.cache_data(ttl="15m", max_entries=20) +def load_orders() -> pd.DataFrame: + return fetch_orders() + + +region = st.selectbox("Region", regions) +orders = load_orders() +filtered_orders = orders[orders["region"] == region] +``` + +Use `st.cache_resource` for shared resources, and do not wrap `st.connection`. + +```python +# GOOD: Shared model or client +@st.cache_resource +def load_model(): + return SentenceTransformer("all-MiniLM-L6-v2") +``` + +Render stable UI before slow calls. Streamlit emits UI updates top to bottom during each rerun, so slow code before downstream elements leaves faded stale content from the previous run on screen while it runs. Render fast UI first, reserve the slow result's position with `st.container()`, then fill that slot once the work completes — wrap the slow work in `with container.skeleton():` to show a loading placeholder, and write results explicitly to the container (e.g. `container.dataframe(...)`), since the block doesn't redirect bare `st.*` calls into it. Avoid standalone `st.empty()`/`st.skeleton()` placeholders that you fill after slow work: the delay unmounts the old element and resets stateful widgets (e.g. a dataframe's scroll, sort, and selection), whereas a reserved container keeps it mounted at a stable position. Give stateful elements a stable `key`. + +```python +# BAD: The whole page is stuck behind a slow load and greys out +orders = load_orders() # ~5s +st.title("Orders") +region = st.selectbox("Region", regions) +st.dataframe(orders) + +# GOOD: Title and filter paint immediately; a container reserves the table's slot and +# shows a skeleton while it loads, so the table keeps its state at a stable position. +st.title("Orders") +region = st.selectbox("Region", regions) +table_slot = st.container() # Reserve the table's position up front +with table_slot.skeleton(): + orders = load_orders() + table_slot.dataframe(orders, key="orders") # Write into the reserved slot +``` + +See `performance.md` for the rendering-order details and a fuller placeholder example. + +Use fragments for independent sections that can rerun separately from the page. + +```python +@st.fragment(run_every="30s") +def live_metrics(): + st.metric("Active users", get_active_user_count()) + + +live_metrics() +``` + +Use forms to batch related inputs when intermediate changes would trigger expensive work. + +```python +# BAD: Search runs after each widget update +query = st.text_input("Search") +category = st.selectbox("Category", categories) +results = search(query, category) + +# GOOD: Search runs only when the user submits +with st.form("search", border=False): + query = st.text_input("Search") + category = st.selectbox("Category", categories) + submitted = st.form_submit_button("Search", icon=":material/search:") + +if submitted: + results = search(query, category) +``` + +For as-you-type search, use `st.text_input(..., type="search", live=True)` inside a `@st.fragment` instead of a form. Keep expensive work out of that fragment, or use a longer delay such as `live="500ms"`. + +If some inputs must rerun to update others (for example, dependent options), use `on_change="ignore"` on the remaining inputs instead of a form. This is an advanced pattern; see "Skip reruns on individual widgets" in `performance.md` for an example and caveats. + +Do not put expensive work unguarded inside tabs or expanders. Hidden tab content and collapsed expander content still compute unless you opt into dynamic state and guard the work. + +```python +# BAD: Heavy content runs even when the tab is hidden +overview, details = st.tabs(["Overview", "Details"]) +with details: + render_expensive_details() + +# GOOD: Heavy content only runs when the tab is selected +overview, details = st.tabs(["Overview", "Details"], on_change="rerun") +if details.open: + with details: + render_expensive_details() +``` + +```python +# GOOD: Heavy expander content only runs when opened +details = st.expander("Advanced diagnostics", on_change="rerun") +if details.open: + with details: + run_diagnostics() +``` + +## Data and charts + +Prefer Vega-based charts over pyplot and Plotly. Use `st.echarts_chart` when you already have an Apache ECharts option or a `pyecharts` chart rather than a third-party component. Pass `alt=` with the chart's takeaway (on ECharts, `alt` replaces the generated description). + +```python +# GOOD: Native charts for common cases +st.line_chart(df, x="date", y="revenue", alt="Monthly revenue trend") +st.bar_chart(df, x="category", y="orders", alt="Orders by category") +st.scatter_chart( + df, x="revenue", y="margin", color="segment", alt="Margin versus revenue by segment" +) + +# GOOD: Altair for complex charts +chart = ( + alt.Chart(df) + .mark_line() + .encode( + x=alt.X("date:T", title="Date"), + y=alt.Y("revenue:Q", title="Revenue"), + color="region:N", + ) +) +st.altair_chart(chart, alt="Revenue by region over time") +``` + +Keep sensitive data out of frontend payloads. Hiding a dataframe column only hides it visually; pre-filter sensitive columns before display. + +```python +# BAD: Secret column is still sent to the browser +st.dataframe(df, column_config={"api_token": None}) + +# GOOD: Remove sensitive data before display +safe_df = df.drop(columns=["api_token"]) +st.dataframe(safe_df) +``` + +## Widgets and state + +Prefer modern selection widgets for compact choices. + +```python +# BAD: Horizontal radio for a compact mode switch +view = st.radio("View", ["Summary", "Details"], horizontal=True) + +# GOOD: Segmented control for single selection +view = st.segmented_control("View", ["Summary", "Details"]) + +# GOOD: Pills for a few multi-select options +tags = st.pills( + "Tags", + ["New", "Active", "At risk"], + selection_mode="multi", +) +``` + +Initialize session state in one clear place and avoid module-level mutable state for per-user data. + +```python +# BAD: Shared across users when imported +filters = {} + +# GOOD: Per-user state +st.session_state.setdefault("filters", {}) +st.session_state.setdefault("selected_account", None) +``` + +Use widget keys when widgets repeat, parameters change dynamically, or code needs programmatic access. + +```python +# BAD: Changing category changes widget identity and can reset input +query = st.text_input(f"Search {category}") + +# GOOD: Stable widget identity and session-state access +query = st.text_input(f"Search {category}", key="search_query") +``` + +Sync a widget to the URL with `bind="query-params"` rather than hand-rolling `st.query_params`. + +```python +# BAD: Manual read/write plumbing that crashes on an unexpected URL value +default = st.query_params.get("sort", SORTS[0]) +sort = st.selectbox("Sort", SORTS, index=SORTS.index(default)) +st.query_params["sort"] = sort + +# GOOD: Streamlit keeps the widget and the URL in sync +sort = st.selectbox("Sort", SORTS, key="sort", bind="query-params") +``` + +## Secrets and queries + +Store credentials in `st.secrets`, keep `.streamlit/secrets.toml` out of git, and use parameterized queries for user-provided values. + +```python +# BAD: Hard-coded secret and SQL string interpolation +api_key = "my-hardcoded-api-key" +df = conn.query(f"SELECT * FROM orders WHERE region = '{region}'") +``` + +```python +# GOOD: Secret from st.secrets and parameter binding +api_key = st.secrets["openai_api_key"] +df = conn.query( + "SELECT * FROM orders WHERE region = :region", + params={"region": region}, +) +``` + +```gitignore +# GOOD: Keep local secrets out of source control +.streamlit/secrets.toml +``` diff --git a/.agents/skills/developing-with-streamlit/references/ccv2-packaged-components.md b/.agents/skills/developing-with-streamlit/references/ccv2-packaged-components.md new file mode 100644 index 0000000000..32002d9ff6 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/references/ccv2-packaged-components.md @@ -0,0 +1,230 @@ +## Packaged CCv2 components (template-only, mandatory) + +For packaged CCv2 components, agents **MUST** use Streamlit's official template as the starting point for every new component project. + +- [Streamlit component-template](https://github.com/streamlit/component-template) + +Never hand-scaffold the package/manifest/build layout and never copy/paste a packaged component scaffold from blog posts, gists, docs, or other internet sources. + +If a request starts from a non-template scaffold, stop and regenerate from the template first, then port logic into the generated project. + +Follow your generated project's README. **Only keep reading if you need to debug template wiring or customize behavior after template generation.** + +## Contents + +- Agent policy: template-only (mandatory) +- Prerequisites (packaged components) +- Start inline, then graduate to packaged +- Frontend framework note (React is optional) +- TypeScript support (recommended) +- Generate a new CCv2 component project +- Dev loop (template default) +- Packaged component workflow (copy/paste checklist) +- Verify the build output (prevents most load failures) +- React template data flow (critical — don't skip `index.tsx`) +- Template invariants (don’t break these) +- Rename checklist (avoid placeholder-name drift) +- Allowed customizations (after template generation only) +- Verification recommendation + +### Agent policy: template-only (mandatory) + +If the request is for a packaged CCv2 component: + +- Start from the official template first (no exceptions). +- Never manually scaffold a custom package/manifest/build layout before template generation. +- Never copy a packaged component scaffold from the internet, even as a "starting point." +- If given existing non-template scaffolding, regenerate from the template and migrate code into it. +- Customize only after generation so you retain known-good packaging defaults. +- **NEVER introduce v1 APIs when customizing the template.** The template generates correct v2 code. When you modify `__init__.py`, JS/TS files, or `example.py`, use ONLY v2 APIs (`st.components.v2.component`, `setStateValue`, `setTriggerValue`, `parentElement`, `data`). Do NOT import `st.components.v1`, do NOT use `declare_component()`, do NOT use `Streamlit.setComponentValue()` or any v1 JavaScript globals. See "v1 contamination" in [ccv2-troubleshooting.md](ccv2-troubleshooting.md) for the full banned list. + +### Prerequisites (packaged components) + +- **Python build tooling**: `uv` (recommended) + `cookiecutter`. +- **Frontend build tooling**: Node.js + npm. + +### Start inline, then graduate to packaged + +Inline components are great for getting started quickly. Move to a packaged component when you hit any of these: + +- You need **multiple frontend files** (components/modules) instead of one big string. +- You want to pull in **frontend libraries** (npm deps) and run a bundler. +- You need **tests**, CI, versioning, or distribution (PyPI/private index). + +### Frontend framework note (React is optional) + +The official Streamlit `component-template` v2 supports both **React + TypeScript (Vite)** and **Pure TypeScript (Vite)** (no React). CCv2 also works with **any frontend framework that compiles to JavaScript** (Svelte, Vue, Angular, vanilla TS/JS, etc.). + +The only requirement is that you produce JS/CSS assets into your component’s `asset_dir`, then register them from Python via `js="..."` and `css="..."` using **asset-dir-relative** paths/globs. `html=` is always inline markup, never a path: `html="index.html"` renders the literal text. + +### TypeScript support (recommended) + +For end-to-end type safety while authoring the frontend, install `@streamlit/component-v2-lib`: + +- [npm package](https://www.npmjs.com/package/@streamlit/component-v2-lib) +- [docs](https://docs.streamlit.io/develop/api-reference/custom-components/component-v2-lib) + +It provides TypeScript types like `FrontendRenderer` / `FrontendRendererArgs` so your `export default` renderer gets a **typed** `data` payload and typed state/trigger keys via generics. + +### Generate a new CCv2 component project + +This command is the required starting point for every packaged CCv2 component: + +```bash +uvx --from cookiecutter cookiecutter gh:streamlit/component-template --directory cookiecutter/v2 +``` + +If you run this non-interactively, pass explicit cookiecutter values (do not rely on defaults): + +Template keys: + +- `author_name` +- `author_email` +- `project_name` +- `package_name` +- `import_name` +- `description` +- `open_source_license` +- `framework` + +Recommended non-interactive invocation: + +This sample uses a **hypothetical breadcrumb component** name so the values are concrete and meaningful: + +```bash +uvx --from cookiecutter cookiecutter gh:streamlit/component-template \ + --directory cookiecutter/v2 \ + --no-input \ + author_name="Your Name" \ + author_email="you@example.com" \ + project_name="Streamlit Breadcrumbs" \ + package_name="streamlit-breadcrumbs" \ + import_name="streamlit_breadcrumbs" \ + description="Packaged Streamlit CCv2 breadcrumb component" \ + open_source_license="Apache-2.0" \ + framework="React + Typescript" +``` + +Notes: + +- Choice values must match template options exactly (`framework` is `"React + Typescript"` or `"Pure Typescript"`). +- Passing all keys avoids template placeholder names and post-generation rename churn. + +Offline/airgapped: + +```bash +uvx --from cookiecutter cookiecutter /path/to/component-template --directory cookiecutter/v2 +``` + +### Dev loop (template default) + +From the generated project: + +1. Activate the target project environment before Python/uv commands: + + ```bash + source /path/to/project/.venv/bin/activate + ``` + +2. Build the frontend assets (from `/frontend`): + + ```bash + npm i + npm run build + ``` + +3. Editable install (project root containing `pyproject.toml`): + + ```bash + uv pip install -e . --force-reinstall + ``` + +4. Run the example app with Streamlit: + + ```bash + streamlit run example.py + ``` + +Why this order: + +- Building first ensures `asset_dir` contains the expected files before install/use. +- Reinstalling editable after key renames keeps metadata and import paths in sync. + +### Packaged component workflow (copy/paste checklist) + +Use this when debugging or customizing after generation; it's designed to prevent the common "built assets exist but Streamlit can't load them" failure modes. + +``` +Packaged CCv2 checklist +- [ ] Generate project from `component-template` v2 +- [ ] Confirm this is template-generated (not hand-scaffolded, not copied from internet snippets) +- [ ] Activate the target project environment before Python/uv commands +- [ ] Rename template defaults (`streamlit-component-x`, `streamlit_component_x`, etc.) if needed +- [ ] Build frontend assets into the manifest’s `asset_dir` (template: `frontend/build/`) +- [ ] Editable install the Python package (`uv pip install -e . --force-reinstall`) +- [ ] Verify `js=`/`css=` globs match exactly one file each under `asset_dir` +- [ ] Run via `streamlit run ...` and confirm the component renders/events work +- [ ] If something breaks: read `ccv2-troubleshooting.md`, fix, rebuild, re-verify glob uniqueness +``` + +### Verify the build output (prevents most load failures) + +- Ensure the manifest’s `asset_dir` exists and contains the built assets. +- Ensure each glob you register from Python matches **exactly one** file under `asset_dir`: + - Typical: `js="index-*.js"` and `css="index-*.css"` + - If multiple matches: clean the build output (template: `npm run clean`) and rebuild. + +### React template data flow (critical — don't skip `index.tsx`) + +The React cookiecutter template has a **three-file data flow**. When you pass `data={...}` from Python, it flows through all three files before reaching the rendered component: + +1. **`__init__.py`** — Python wrapper sends `data={"name": name, "testId": test_id, ...}` to the frontend +2. **`index.tsx`** — the bridge file that destructures `data` and passes props to the React component: `const { name, testId } = data;` → `` +3. **`MyComponent.tsx`** — receives props and renders the UI: `` + +**You MUST edit all three files** when adding new data fields. The most common mistake is editing `__init__.py` and `MyComponent.tsx` but forgetting `index.tsx`. If you skip `index.tsx`, your new data fields are sent from Python but never reach the React component — props will be `undefined`. + +**`data-testid` propagation**: When adding `data-testid` attributes for QA/testing, ensure the test ID value flows through the entire chain: +- Python sends it via `data={"testId": "my-button"}` +- `index.tsx` extracts it: `const { testId } = data;` and passes it: `` +- `MyComponent.tsx` renders it: `` + +If any layer is missing, the `data-testid` won't appear on the rendered element. + +### Template invariants (don't break these) + +You typically shouldn't need to touch these, but they explain most "why won't this load?" failures: + +- **Component key**: the Python registration key must match the manifest: `"."`. **Do NOT change the component name that the template generates** — the template wires the fully-qualified name correctly across `__init__.py`, the inner `pyproject.toml` manifest, and the `MANIFEST.in`. Changing it in one place without updating all others will cause `StreamlitAPIException: Component '...' must be declared in pyproject.toml with asset_dir to use file-backed js`. +- **Manifest must ship inside the Python package**: the template places a minimal CCv2 manifest at `/pyproject.toml` with `asset_dir = "frontend/build"`. Do NOT rename `[[tool.streamlit.component.components]]` to anything else — this exact TOML key is required. +- **Asset paths are asset-dir-relative strings**: `js="index-*.js"` (template default output) or `js="assets/index-*.js"` (if you configured an `assets/` subdir). +- **Globs must match exactly one file**: if `index-*.js` matches multiple hashed builds, clean the build output (`npm run clean`) and rebuild. + +### Rename checklist (avoid placeholder-name drift) + +Template defaults like `streamlit-component-x` / `streamlit_component_x` should be replaced everywhere early. + +Rename all of these together: + +- Root folder name (optional but recommended for clarity). +- Distribution name (`[project].name`) in root `pyproject.toml`. +- Import package directory (`streamlit_`). +- In-package manifest file and contents (`/pyproject.toml`). +- Wrapper registration key: + - `st.components.v2.component(".", ...)` +- `MANIFEST.in` and `[tool.setuptools.*]` references. +- README/example imports and frontend package name. + +### Allowed customizations (after template generation only) + +Keep the blast radius small: + +- If you change output layout, update only the `js=`/`css=` asset-dir-relative globs in the Python wrapper. +- For Vite, keep `base: "./"` so relative URLs work when served from Streamlit’s component URLs. + +### Verification recommendation + +Validate packaged components with `streamlit run ...`, not plain `python -c "import ..."` checks. + +- Streamlit discovers component manifests as part of runtime setup. +- Plain import checks can report false-negative `asset_dir` registration errors for otherwise-correct packaged components. diff --git a/.agents/skills/developing-with-streamlit/references/ccv2-state-sync.md b/.agents/skills/developing-with-streamlit/references/ccv2-state-sync.md new file mode 100644 index 0000000000..8b407b5b8a --- /dev/null +++ b/.agents/skills/developing-with-streamlit/references/ccv2-state-sync.md @@ -0,0 +1,150 @@ +## State sync patterns (JS ↔ Python) + +This reference shows the canonical CCv2 “controlled component” loop and the most common pitfalls when syncing state between JavaScript and Python. + +## Contents + +- Mental model +- Canonical pattern: controlled text input + - JavaScript (hydrate from `data`, emit via `setStateValue`) + - Python wrapper (feed state back down via `data`) +- Defaults: when to use `default=...` (and why it fails) +- Python → JS hydration: initial-only vs true sync +- Session State timing: don’t mutate after mount +- Troubleshooting checklist + +### Mental model + +- **Frontend state emission (JS → Python)**: you explicitly call `setStateValue(key, value)` or `setTriggerValue(key, value)`. +- **Frontend state hydration (Python → JS)**: your JS reads `component.data` and updates the DOM accordingly. +- There is no built-in “two-way binding”: you must implement both sides. + +### Canonical pattern: controlled text input + +This is modeled after Streamlit’s own CCv2 e2e example. + +#### JavaScript (hydrate from `data`, emit via `setStateValue`) + +Key guideline: only assign to the input when it’s different, or you’ll fight the user’s cursor. + +```js +export default function (component) { + const { parentElement, data, setStateValue } = component + + const label = parentElement.querySelector("label") + const input = parentElement.querySelector("input") + if (!label || !input) return + + label.innerText = data.label + + const nextValue = data.value ?? "" + if (input.value !== nextValue) { + input.value = nextValue + } + + input.onkeydown = e => { + if (e.key === "Enter") { + setStateValue("value", e.target.value) + } + } +} +``` + +#### Python wrapper (feed state back down via `data`) + +```python +import streamlit as st + +_COMPONENT = st.components.v2.component( + "interactive_text_input", + html=""" + + + """, + js=JS, # inline JS string from above +) + + +def interactive_text_input(*, label: str, initial_value: str, key: str): + # 1) Read current component state from Session State (if it exists) + component_state = st.session_state.get(key, {}) + + # 2) Compute the value you want the UI to display + value = component_state.get("value", initial_value) + + # 3) Send it down to the frontend via `data` + return _COMPONENT( + key=key, + data={"label": label, "value": value}, + ) + + +KEY = "my_text_input" + +if st.button("Make it say Hello World"): + st.session_state.setdefault(KEY, {})["value"] = "Hello World" + +interactive_text_input(label="Enter something", initial_value="Initial Text", key=KEY) +``` + +### Defaults: when to use `default=...` (and why it fails) + +`default={...}` is optional. Use it when you want Streamlit to initialize missing state keys for a mounted instance. + +Rules: + +- Defaults apply only to **state** keys (not triggers). +- Every key in `default` must have a corresponding `on__change` callback parameter when mounting, or Streamlit raises. + +Pattern: + +```python +result = _COMPONENT( + key=key, + data={"value": value}, + default={"value": value}, + on_value_change=lambda: None, # required if using default["value"] +) +``` + +### Python → JS hydration: initial-only vs true sync + +You’ll see two patterns in the wild: + +- **Initial-only hydration**: JS reads `data.initialX` on first mount only. This is useful for *initialization* but it will **not** reflect later Python changes. +- **True sync (controlled)**: JS reconciles its UI from `data.value` on every render, and only writes when changed. + +Initial-only example (pitfall for sync): + +```js +// If you guard hydration with hasMounted, Python changes won't propagate. +if (typeof data?.initialText !== "undefined" && !hasMountedForKey) { + input.value = String(data.initialText) +} +hasMounted[key] = true +``` + +True sync approach (recommended when Python can update the UI): + +```js +const nextValue = data.value ?? "" +if (input.value !== nextValue) input.value = nextValue +``` + +### Session State timing: don’t mutate after mount + +Streamlit may raise if you modify `st.session_state..` **after** the component with that key has been instantiated in the same run. + +Safe patterns: + +- Update `st.session_state[key][...]` **before** mounting the component (e.g., in a button handler placed above the mount call). +- Or update state in a different run (trigger a rerun after setting state). +- If the mount passes any `on__change` callback, Streamlit silently ignores Python writes to state keys that lack a matching `on__change` callback. Pass a no-op callback (for example, `on_value_change=lambda: None`) for every state key you set from Python. + +### Troubleshooting checklist + +- **Cursor jumps / typing feels broken**: ensure your JS only assigns `input.value` when it differs from the `data` value. +- **Python updates don’t reflect in UI**: confirm you pass the updated values via `data` every run; avoid initial-only hydration guards if you want true sync. +- **`default` raises**: ensure every default key has a corresponding `on__change` callback parameter. +- **Session state mutation error**: move `st.session_state[key][...] = ...` earlier in the script (before mount), or restructure into a two-run flow (set state then rerun). +- **Python write to component state has no effect**: if the mount passes any `on__change` callback, also pass one (a no-op is fine) for each state key you set from Python. diff --git a/.agents/skills/developing-with-streamlit/references/ccv2-theme-css-variables.md b/.agents/skills/developing-with-streamlit/references/ccv2-theme-css-variables.md new file mode 100644 index 0000000000..f16d5b305d --- /dev/null +++ b/.agents/skills/developing-with-streamlit/references/ccv2-theme-css-variables.md @@ -0,0 +1,252 @@ +## Streamlit theme CSS variables for CCv2 components (`--st-*`) + +Streamlit injects a set of `--st-*` CSS custom properties into CCv2 components so your component can match the app’s active theme from within your component CSS (including when `isolate_styles=True` and you’re rendering inside a shadow root). + +**Recommendation:** Prefer `var(--st-…)` over hard-coded colors and sizes. These variables automatically adapt to a user's current Streamlit theme (light/dark/custom), so most components **do not** need separate “dark mode vs light mode” styling. + +## Contents + +- Quick start +- Gotchas: serialization + fallbacks +- Cheat sheet: the 90% variables (intent → `--st-*`) +- Foundation tokens (surfaces, text, borders, shape) +- Typography tokens +- Data display tokens (dataframes/tables) +- Data visualization tokens (chart palettes) +- Semantic/status palette (red/green/etc.) +- Appendix: full variable index (alphabetical) + +### Quick start + +Use them like any CSS variable: + +```css +.card { + background: var(--st-secondary-background-color); + color: var(--st-text-color); + border: 1px solid var(--st-border-color); + border-radius: var(--st-base-radius); +} + +.primaryButton { + background: var(--st-primary-color); + color: var(--st-background-color); + border-radius: var(--st-button-radius); +} +``` + +### Gotchas: serialization rules + safe fallbacks + +These variables originate from Streamlit’s theme object and are serialized into strings: + +- **Strings**: passed through (e.g. `--st-primary-color: #ff4b4b`). +- **Numbers**: stringified (e.g. `--st-base-font-weight: 400`). +- **Booleans**: become `"1"` or `"0"` (e.g. `--st-link-underline`). +- **Arrays**: become a comma-joined string (e.g. `--st-heading-font-sizes: 2.75rem,2.25rem,...`). + - If you need individual items in JS, split on `","`. +- **Missing values (`null` / `undefined`)**: become `unset` so consumers fall back to initial/inherited CSS behavior. + +### Cheat sheet: the 90% variables (intent → `--st-*`) + +Use this section as your starting point. It covers what most components need most of the time. + +| Intent | Variables | +| ------------------------- | ---------------------------------------------------------------------- | +| App/page background | `--st-background-color` | +| Panel/card background | `--st-secondary-background-color` | +| Body text | `--st-text-color` | +| Headings | `--st-heading-color`, `--st-heading-font` | +| Primary accent / emphasis | `--st-primary-color` | +| Links | `--st-link-color`, `--st-link-underline` | +| Borders / dividers | `--st-border-color`, `--st-border-color-light` | +| Widget outline borders | `--st-widget-border-color` | +| Corner radius | `--st-base-radius`, `--st-button-radius` | +| Code blocks | `--st-code-background-color`, `--st-code-text-color`, `--st-code-font` | + +### Foundation tokens (surfaces, text, borders, shape) + +#### Surfaces and content colors + +- `--st-background-color` (page background) +- `--st-secondary-background-color` (panels, cards, containers) +- `--st-text-color` (default text) +- `--st-heading-color` (derived heading color) +- `--st-primary-color` (brand / accent) +- `--st-link-color` (link color) +- `--st-link-underline` (boolean serialized to `"1"` / `"0"`) + +#### Borders and separators + +- `--st-border-color` (default borders/dividers) +- `--st-border-color-light` (derived lighter border) +- `--st-widget-border-color` (widget borders) + +#### Shape (radii) + +- `--st-base-radius` +- `--st-button-radius` + +#### Code block colors + +- `--st-code-background-color` +- `--st-code-text-color` + +### Typography tokens + +#### Font families + +- `--st-font` (body font) +- `--st-heading-font` +- `--st-code-font` + +#### Body sizing and weights + +- `--st-base-font-size` +- `--st-base-font-weight` (number) + +#### Headings (H1–H6) + +Arrays (comma-joined): + +- `--st-heading-font-sizes` (array; typically 6 values for H1–H6) +- `--st-heading-font-weights` (array; typically 6 values for H1–H6) + +Per-level convenience variables: + +- `--st-heading-font-size-1` +- `--st-heading-font-size-2` +- `--st-heading-font-size-3` +- `--st-heading-font-size-4` +- `--st-heading-font-size-5` +- `--st-heading-font-size-6` +- `--st-heading-font-weight-1` (number) +- `--st-heading-font-weight-2` (number) +- `--st-heading-font-weight-3` (number) +- `--st-heading-font-weight-4` (number) +- `--st-heading-font-weight-5` (number) +- `--st-heading-font-weight-6` (number) + +#### Code typography + +- `--st-code-font-size` +- `--st-code-font-weight` (number) + +#### Metric value + +- `--st-metric-value-font-size` +- `--st-metric-value-font-weight` (number) + +### Data display tokens (dataframes/tables) + +- `--st-dataframe-border-color` +- `--st-dataframe-header-background-color` +- `--st-dataframe-header-text-color` + +### Data visualization tokens (chart palettes) + +Chart palette variables are **arrays serialized as comma-joined strings**: + +- `--st-chart-categorical-colors` (discrete series) +- `--st-chart-sequential-colors` (low → high) +- `--st-chart-diverging-colors` (negative ↔ positive around a midpoint) + +If you need the palette values in JS, split on commas: + +```js +export default function (component) { + const { parentElement } = component; + + const host = parentElement.host ?? parentElement; + const raw = getComputedStyle(host) + .getPropertyValue('--st-chart-categorical-colors') + .trim(); + const palette = raw ? raw.split(',') : []; +} +``` + +### Semantic/status palette + +These are best for status UI (badges, alerts, validation messages), not for primary layout surfaces. + +Each “family” typically comes in three variants: + +- **Base**: `--st--color` +- **Background**: `--st--background-color` +- **Text**: `--st--text-color` + +Families: + +- Red: `--st-red-color`, `--st-red-background-color`, `--st-red-text-color` +- Orange: `--st-orange-color`, `--st-orange-background-color`, `--st-orange-text-color` +- Yellow: `--st-yellow-color`, `--st-yellow-background-color`, `--st-yellow-text-color` +- Blue: `--st-blue-color`, `--st-blue-background-color`, `--st-blue-text-color` +- Green: `--st-green-color`, `--st-green-background-color`, `--st-green-text-color` +- Violet: `--st-violet-color`, `--st-violet-background-color`, `--st-violet-text-color` +- Gray: `--st-gray-color`, `--st-gray-background-color`, `--st-gray-text-color` + +### Appendix: full variable index (alphabetical) + +- `--st-background-color` +- `--st-base-font-size` +- `--st-base-font-weight` +- `--st-base-radius` +- `--st-blue-background-color` +- `--st-blue-color` +- `--st-blue-text-color` +- `--st-border-color` +- `--st-border-color-light` +- `--st-button-radius` +- `--st-chart-categorical-colors` +- `--st-chart-diverging-colors` +- `--st-chart-sequential-colors` +- `--st-code-background-color` +- `--st-code-font` +- `--st-code-font-size` +- `--st-code-font-weight` +- `--st-code-text-color` +- `--st-dataframe-border-color` +- `--st-dataframe-header-background-color` +- `--st-dataframe-header-text-color` +- `--st-font` +- `--st-gray-background-color` +- `--st-gray-color` +- `--st-gray-text-color` +- `--st-green-background-color` +- `--st-green-color` +- `--st-green-text-color` +- `--st-heading-color` +- `--st-heading-font` +- `--st-heading-font-size-1` +- `--st-heading-font-size-2` +- `--st-heading-font-size-3` +- `--st-heading-font-size-4` +- `--st-heading-font-size-5` +- `--st-heading-font-size-6` +- `--st-heading-font-sizes` +- `--st-heading-font-weight-1` +- `--st-heading-font-weight-2` +- `--st-heading-font-weight-3` +- `--st-heading-font-weight-4` +- `--st-heading-font-weight-5` +- `--st-heading-font-weight-6` +- `--st-heading-font-weights` +- `--st-link-color` +- `--st-link-underline` +- `--st-metric-value-font-size` +- `--st-metric-value-font-weight` +- `--st-orange-background-color` +- `--st-orange-color` +- `--st-orange-text-color` +- `--st-primary-color` +- `--st-red-background-color` +- `--st-red-color` +- `--st-red-text-color` +- `--st-secondary-background-color` +- `--st-text-color` +- `--st-violet-background-color` +- `--st-violet-color` +- `--st-violet-text-color` +- `--st-widget-border-color` +- `--st-yellow-background-color` +- `--st-yellow-color` +- `--st-yellow-text-color` diff --git a/.agents/skills/developing-with-streamlit/references/ccv2-troubleshooting.md b/.agents/skills/developing-with-streamlit/references/ccv2-troubleshooting.md new file mode 100644 index 0000000000..bbc8aa4365 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/references/ccv2-troubleshooting.md @@ -0,0 +1,153 @@ +## Troubleshooting CCv2 components + +## Contents + +- **v1 contamination (most common failure)** +- Packaged assets and manifests (`asset_dir`, component key) +- Renamed project/package still shows old template names +- Inline strings vs file-backed assets (path heuristic) +- Globs (0 matches or multiple matches) +- Defaults, callbacks, and missing result attributes +- Keys (Python `key=` vs frontend `key`) +- Shadow DOM / `isolate_styles` surprises +- Frontend build gotchas +- DOM clobbering (overwriting injected HTML/CSS) + +### v1 contamination (most common failure) + +The single most common cause of broken CCv2 components is accidentally mixing in **v1 APIs** from outdated examples, blog posts, or training data. v1 APIs don’t work inside a v2 component. + +Symptoms: +- Component renders as blank/empty iframe +- `Streamlit is not defined` errors in browser console +- `setComponentValue is not a function` errors +- Component never communicates back to Python + +Check your code for these **banned patterns** and replace them: + +| Banned (v1) | Correct (v2) | +|------------------------------------------|-------------------------------------------------------| +| `st.components.v1` | `st.components.v2.component(...)` | +| `components.declare_component()` | `st.components.v2.component(...)` | +| `components.html()` | `st.iframe()` / `st.html()` for static HTML, or `st.components.v2.component(...)` with `html=` when it needs events | +| `Streamlit.setComponentValue(val)` | `setStateValue("key", val)` or `setTriggerValue(...)` | +| `Streamlit.setFrameHeight()` | Remove entirely (v2 handles sizing) | +| `Streamlit.setComponentReady()` | Remove entirely (v2 has no ready signal) | +| `window.Streamlit` | Use destructured args from `export default function` | +| `window.parent.postMessage(...)` | Use `setStateValue` / `setTriggerValue` | +| `streamlit-component-lib` (npm) | `@streamlit/component-v2-lib` (if types needed) | +| `function sendMessageToStreamlitClient` | Remove entirely; use v2 callback args | + +Fix: search all `.py` and `.js`/`.ts`/`.tsx` files for these patterns. If any are found, rewrite using the v2 equivalents above. The cookiecutter template generates correct v2 code — if you started from the template, the contamination is in your customizations. + +### Packaged assets and manifests (`asset_dir`, component key) + +#### “Component '' must be declared in pyproject.toml with asset_dir to use file-backed js/css.” + +You passed a **path-like** `js=`/`css=` string (like `index-*.js` or `assets/index-*.js`) but Streamlit can’t find an `asset_dir` for this component key. + +Fix: + +- If you want **inline JS/CSS**, pass a **multi-line** string with the actual code (not a path). +- If you want **packaged assets**, ensure: + - Your wheel includes a `pyproject.toml` with `[[tool.streamlit.component.components]] ... asset_dir = ...` + - You call `st.components.v2.component(".", js="...", css="...")` with the matching fully-qualified key. + +Important context: + +- This error is expected if you test packaged wrappers via plain Python import in some environments. +- Prefer `streamlit run ...` for packaged verification because manifest discovery is part of Streamlit runtime initialization. + +### Inline strings vs file-backed assets (path heuristic) + +CCv2 uses a heuristic: strings that “look like” paths are treated as file references. A string with a line break inside it is always treated as inline content. Leading and trailing newlines are stripped first, so they don't count. + +Fix: + +- Prefer triple-quoted multi-line strings for inline `html`/`css`/`js`. +- Avoid single-line minified JS/CSS in `js=`/`css=`; if you must use it, put a line break inside the code. + +### Globs (0 matches or multiple matches) + +Globs must match **exactly one** file under `asset_dir`. + +Fix: + +- Clean the build output directory before rebuilding. +- Make your bundler output a predictable `index-.js` / `index-.css` (or `assets/index-...` if you emit into an `assets/` subdir). +- If you started from Streamlit’s `component-template`, run `npm run clean` from your `frontend/` directory to clear the `build/` output so `index-*.js` matches exactly one file. + +### Renamed project/package still shows old template names + +Symptoms: + +- Old names like `streamlit-component-x` / `streamlit_component_x` remain in paths or metadata. +- Imports, manifest component keys, and registration keys no longer align. + +Fix: + +- Rename/update all related surfaces together: + - root `pyproject.toml` project name + - import package folder and `MANIFEST.in` paths + - `[tool.setuptools.packages.find]` and `[tool.setuptools.package-data]` + - in-package manifest (`/pyproject.toml`) + - wrapper registration key (`"."`) + - README/example imports and install commands +- Rebuild frontend and reinstall editable package after rename. + +### Defaults, callbacks, and missing result attributes + +#### `default={...}` raises "is not a valid state name" / missing result attributes + +Defaults only apply to **state keys**, and Streamlit expects those keys to be declared via `on__change` callback parameters at mount time. + +Fix: + +- If you pass `default={"value": ...}`, also pass `on_value_change=lambda: None`. +- For triggers, don’t expect defaults; triggers are transient and default to `None`. + +#### Trigger never fires inside `st.form` + +`setTriggerValue` is ignored when the component is inside `st.form`; the browser console logs a warning instead. Inside a form, use `setStateValue` and let the form’s submit button commit it. + +### Keys (Python `key=` vs frontend `key`) + +- Python `key=` is the user-visible Streamlit element key. +- The frontend also receives a `key` string that is **generated by Streamlit** and is not the same as the Python `key` unless you explicitly pass the user key through `data`. + +Fix: + +- If your frontend needs a stable identifier, pass it in `data={"user_key": key, ...}`. + +### Shadow DOM / `isolate_styles` surprises + +#### Shadow DOM (`isolate_styles=True`) surprises + +With `isolate_styles=True` (default): + +- Your component is mounted in a **shadow root**. +- `parentElement` is a `ShadowRoot`. +- Global CSS (like Tailwind injected into the document) won’t automatically style your component. + +Fix: + +- Keep `isolate_styles=True` for safety and use CSS variables and component-local styles. +- Use `isolate_styles=False` only when you intentionally need global styling behavior. + +### Frontend build gotchas (Vite) + +If you deviate from the template’s Vite config (or you’re wiring Vite into an existing repo), these are the common footguns: + +- **Missing `base: "./"`**: relative asset URLs can break when served from Streamlit’s component URL path. +- **Stale build artifacts**: Vite outputs hashed filenames; if you keep old builds around, `index-*.js` can match multiple files. Clean the build dir before rebuilding. + +### DOM clobbering (overwriting injected HTML/CSS) + +#### Accidentally overwriting your component DOM + +If you directly set `parentElement.innerHTML = ...`, you can overwrite the HTML/CSS that Streamlit injected from your `html=`/`css=` arguments. + +Fix: + +- Prefer `querySelector` + modifying children. +- If you need dynamic HTML, create a new child element and set **that** element’s `innerHTML`. diff --git a/.agents/skills/developing-with-streamlit/references/chat-ui.md b/.agents/skills/developing-with-streamlit/references/chat-ui.md new file mode 100644 index 0000000000..0c6675108b --- /dev/null +++ b/.agents/skills/developing-with-streamlit/references/chat-ui.md @@ -0,0 +1,254 @@ + +# Streamlit chat interfaces + +Build conversational UIs with Streamlit's chat elements. + +## Basic chat structure + +```python +import streamlit as st + +if "messages" not in st.session_state: + st.session_state.messages = [] + +# Display chat history +for msg in st.session_state.messages: + with st.chat_message(msg["role"]): + st.write(msg["content"]) + +# Handle new input +if prompt := st.chat_input("Ask a question"): + st.session_state.messages.append({"role": "user", "content": prompt}) + + with st.chat_message("user"): + st.write(prompt) + + with st.chat_message("assistant"): + response = get_response(prompt) # Your LLM call + st.write(response) + + st.session_state.messages.append({"role": "assistant", "content": response}) +``` + +## Streaming responses + +Use `st.write_stream` for token-by-token display. Pass any generator that yields strings, including the OpenAI generator directly: + +```python +def get_streaming_response(prompt): + # Replace with your LLM client (OpenAI, Anthropic, Cortex, etc.) + for chunk in your_llm_client.stream(prompt): + yield chunk + + +with st.chat_message("assistant"): + response = st.write_stream(get_streaming_response(prompt)) + +st.session_state.messages.append({"role": "assistant", "content": response}) +``` + +With OpenAI, you can pass the stream directly: + +```python +from openai import OpenAI + +client = OpenAI() +with st.chat_message("assistant"): + stream = client.chat.completions.create( + model="gpt-4o", + messages=st.session_state.messages, + stream=True, + ) + response = st.write_stream(stream) +``` + +## Controlling input while the response runs + +Use `submit_mode` to control what happens to the chat input after a user submits a message while the script (e.g. an LLM response) is still running: + +```python +# Disable the input until the response finishes (prevents interruptions) +prompt = st.chat_input("Ask a question", submit_mode="disable") + +# Turn the submit button into a stop button so users can cancel a long response +prompt = st.chat_input("Ask a question", submit_mode="stop") +``` + +- `"submit"` (default): the input stays enabled, so users can send new messages while the script runs. +- `"disable"`: the input is disabled after submission and re-enabled when the run completes—useful to avoid interrupting streaming responses. +- `"stop"`: the submit button becomes a stop button during the run; clicking it stops the script, like the app's "Stop" button. + +## Thinking and agent steps + +Use `type="compact"` or `type="step"` on `st.status` or `st.expander` inside a chat message to disclose reasoning without the default bordered container. Prefer `st.status` for live thinking; `st.expander` is fine for static replay from history. + +**Compact thinking expander.** A borderless inline toggle—the ChatGPT/Claude-style "Thought for N seconds" pattern. Use this for a single reasoning block. While work is running, wrap the compact label in `:shimmer[...]` so the text itself is the in-progress cue; update to a static label when complete. + +```python +with st.chat_message("assistant"): + with st.status(":shimmer[Thinking]", type="compact") as status: + st.write(reasoning) + status.update(label="Thought for 4 seconds", state="complete") + + response = st.write_stream(get_streaming_response(prompt)) +``` + +**Step timeline.** Consecutive `type="step"` containers share a vertical connector. Use this for tool calls, retrieval, and multi-stage agent work that should stay visible in the message. + +```python +with st.chat_message("assistant"): + with st.status("Searching docs", type="step"): + sources = search(prompt) + st.write(sources[0]) + + with st.status("Thinking", type="step"): + st.write(reasoning) + + response = st.write_stream(get_streaming_response(prompt, sources)) +``` + +The connector already stops when the next sibling is not a step, so you do not need an empty terminal step before the streamed answer. + +**Combining both.** Nest the step timeline inside a compact status when the details should stay collapsed by default. This is usually the best fit in chat: a "Thought for N seconds" toggle that reveals the chain of thought. + +```python +with st.chat_message("assistant"): + with st.status(":shimmer[Thinking]", type="compact") as status: + with st.status("Searching docs", type="step"): + sources = search(prompt) + st.write(sources[0]) + + with st.status("Planning", type="step"): + st.write(reasoning) + + status.update(label="Thought for 4 seconds", state="complete") + + response = st.write_stream(get_streaming_response(prompt, sources)) +``` + +- Keep `type="step"` containers consecutive. Any other element between them—including an invisible `st.empty()`—starts a new timeline segment. +- A step with no content also ends the timeline, which is useful to split a chain into segments—not as a dummy "done" node before the answer. +- `state` must be `"running"` (default), `"complete"`, or `"error"`—any other value raises an error, including via `status.update(state=...)`. +- Put the status where the work runs so its steps appear as the task runs. Don't gate it behind a button whose only job is to launch the task—running it in response to real input, for example `if prompt := st.chat_input(...)`, is the normal case. + +## Chat message avatars + +Streamlit provides default avatars for "user" and "assistant" roles—only customize if you have a specific need. You can use icons or images: + +```python +# With icons +with st.chat_message("assistant", avatar=":material/robot:"): + st.write(assistant_message) + +# With images +with st.chat_message("user", avatar="https://example.com/avatar.png"): + st.write(user_message) +``` + +## Suggestion chips + +Offer clickable suggestions before the first message. A selected suggestion becomes the first prompt, and the pills disappear once the conversation starts: + +```python +SUGGESTIONS = { + ":blue[:material/help:] What is Streamlit?": "Explain what Streamlit is", + ":green[:material/code:] Show me an example": "Show a simple Streamlit example", +} + +# Replaces the basic example's `if prompt := st.chat_input(...)` +prompt = st.chat_input("Ask a question") + +if not st.session_state.messages: + suggestions = st.empty() + selected = suggestions.pills( + "Try asking:", list(SUGGESTIONS.keys()), label_visibility="collapsed" + ) + if selected: + prompt = SUGGESTIONS[selected] + if prompt: + suggestions.empty() # Hide the pills before the first reply renders + +if prompt: + ... # Same handling as typed input: append, display, and generate the reply +``` + +Show suggestions only while `st.session_state.messages` is empty, and route the selected suggestion through the same `if prompt:` handler as typed input. Appending the suggestion and calling `st.rerun()` skips the reply, because on that rerun `st.chat_input` returns `None`. Render the pills in an `st.empty()` placeholder and clear it once there is a prompt; otherwise they stay on screen above the first reply until the next rerun. + +## File uploads + +Enable file attachments with `accept_file`. When enabled, `st.chat_input` returns a dict-like object with `text` and `files` attributes: + +```python +prompt = st.chat_input( + "Ask about an image", + accept_file=True, + file_type=["jpg", "jpeg", "png"], +) + +if prompt: + with st.chat_message("user"): + if prompt.text: + st.write(prompt.text) + if prompt.files: + st.image(prompt.files[0]) + + # Send to vision model; a message can be text-only, so files may be empty + with st.chat_message("assistant"): + image = prompt.files[0] if prompt.files else None + response = analyze_image(image, prompt.text) + st.write(response) +``` + +Use `accept_file="multiple"` to allow multiple files. + +For typed helpers, import `ChatInputValue` and `UploadedFile` from the public `streamlit.typing` namespace instead of Streamlit's internal modules: + +```python +from streamlit.typing import ChatInputValue, UploadedFile + + +def first_file(submission: ChatInputValue) -> UploadedFile | None: + return submission.files[0] if "files" in submission and submission.files else None +``` + +## Audio input + +Enable voice recording with `accept_audio`. The recorded audio is available as a WAV file: + +```python +prompt = st.chat_input("Say something", accept_audio=True) + +if prompt: + if prompt.audio: + st.audio(prompt.audio) + if prompt.text: + st.write(prompt.text) +``` + +### Dictation with speech-to-text + +Convert audio to text and inject it back into the chat input: + +```python +prompt = st.chat_input("Say something", accept_audio=True, key="chat") + +if prompt and prompt.audio: + # Transcribe with Whisper or another STT model + transcript = openai.audio.transcriptions.create( + model="whisper-1", + file=prompt.audio, + ) + # Set the transcribed text as the next input + st.session_state.chat = transcript.text + st.rerun() +``` + +## References + +- `snowflake-connection.md` — Database queries and Cortex chat example +- `performance.md` — Caching strategies for LLM calls +- [st.chat_message](https://docs.streamlit.io/develop/api-reference/chat/st.chat_message) +- [st.chat_input](https://docs.streamlit.io/develop/api-reference/chat/st.chat_input) +- [st.write_stream](https://docs.streamlit.io/develop/api-reference/write-magic/st.write_stream) +- [st.status](https://docs.streamlit.io/develop/api-reference/status/st.status) +- [st.expander](https://docs.streamlit.io/develop/api-reference/layout/st.expander) diff --git a/.agents/skills/developing-with-streamlit/references/cli.md b/.agents/skills/developing-with-streamlit/references/cli.md new file mode 100644 index 0000000000..4789071280 --- /dev/null +++ b/.agents/skills/developing-with-streamlit/references/cli.md @@ -0,0 +1,190 @@ + +# Using the Streamlit CLI + +The Streamlit CLI is the primary tool for running Streamlit applications and managing configuration. This skill covers all essential commands and configuration options. + +## Running Streamlit apps + +### Basic syntax + +```bash +streamlit run [] [--
.