index
int64 0
0
| repo_id
stringclasses 80
values | file_path
stringlengths 32
137
| content
stringlengths 4
914k
|
|---|---|---|---|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/commands/experimental_query_params.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from typing import Any
from urllib import parse
from streamlit.errors import StreamlitAPIException
from streamlit.proto.ForwardMsg_pb2 import ForwardMsg
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner_utils.script_run_context import get_script_run_ctx
from streamlit.runtime.state.query_params import (
EMBED_OPTIONS_QUERY_PARAM,
EMBED_QUERY_PARAM,
EMBED_QUERY_PARAMS_KEYS,
)
@gather_metrics("experimental_get_query_params")
def get_query_params() -> dict[str, list[str]]:
"""Return the query parameters that is currently showing in the browser's URL bar.
Returns
-------
dict
The current query parameters as a dict. "Query parameters" are the part of the URL that comes
after the first "?".
Example
-------
Let's say the user's web browser is at
`http://localhost:8501/?show_map=True&selected=asia&selected=america`.
Then, you can get the query parameters using the following:
>>> import streamlit as st
>>>
>>> st.experimental_get_query_params()
{"show_map": ["True"], "selected": ["asia", "america"]}
Note that the values in the returned dict are *always* lists. This is
because we internally use Python's urllib.parse.parse_qs(), which behaves
this way. And this behavior makes sense when you consider that every item
in a query string is potentially a 1-element array.
"""
ctx = get_script_run_ctx()
if ctx is None:
return {}
ctx.mark_experimental_query_params_used()
# Return new query params dict, but without embed, embed_options query params
return _exclude_keys_in_dict(
parse.parse_qs(ctx.query_string, keep_blank_values=True),
keys_to_exclude=EMBED_QUERY_PARAMS_KEYS,
)
@gather_metrics("experimental_set_query_params")
def set_query_params(**query_params: Any) -> None:
"""Set the query parameters that are shown in the browser's URL bar.
.. warning::
Query param `embed` cannot be set using this method.
Parameters
----------
**query_params : dict
The query parameters to set, as key-value pairs.
Example
-------
To point the user's web browser to something like
"http://localhost:8501/?show_map=True&selected=asia&selected=america",
you would do the following:
>>> import streamlit as st
>>>
>>> st.experimental_set_query_params(
... show_map=True,
... selected=["asia", "america"],
... )
"""
ctx = get_script_run_ctx()
if ctx is None:
return
ctx.mark_experimental_query_params_used()
msg = ForwardMsg()
msg.page_info_changed.query_string = _ensure_no_embed_params(
query_params, ctx.query_string
)
ctx.query_string = msg.page_info_changed.query_string
ctx.enqueue(msg)
def _exclude_keys_in_dict(
d: dict[str, Any], keys_to_exclude: list[str]
) -> dict[str, Any]:
"""Returns new object but without keys defined in keys_to_exclude."""
return {
key: value for key, value in d.items() if key.lower() not in keys_to_exclude
}
def _extract_key_query_params(
query_params: dict[str, list[str]], param_key: str
) -> set[str]:
"""Extracts key (case-insensitive) query params from Dict, and returns them as Set of str."""
return {
item.lower()
for sublist in [
[value.lower() for value in query_params[key]]
for key in query_params
if key.lower() == param_key and query_params.get(key)
]
for item in sublist
}
def _ensure_no_embed_params(
query_params: dict[str, list[str] | str], query_string: str
) -> str:
"""Ensures there are no embed params set (raises StreamlitAPIException) if there is a try,
also makes sure old param values in query_string are preserved. Returns query_string : str.
"""
# Get query params dict without embed, embed_options params
query_params_without_embed = _exclude_keys_in_dict(
query_params, keys_to_exclude=EMBED_QUERY_PARAMS_KEYS
)
if query_params != query_params_without_embed:
raise StreamlitAPIException(
"Query param embed and embed_options (case-insensitive) cannot be set using set_query_params method."
)
all_current_params = parse.parse_qs(query_string, keep_blank_values=True)
current_embed_params = parse.urlencode(
{
EMBED_QUERY_PARAM: list(
_extract_key_query_params(
all_current_params, param_key=EMBED_QUERY_PARAM
)
),
EMBED_OPTIONS_QUERY_PARAM: list(
_extract_key_query_params(
all_current_params, param_key=EMBED_OPTIONS_QUERY_PARAM
)
),
},
doseq=True,
)
query_string = parse.urlencode(query_params, doseq=True)
if query_string:
separator = "&" if current_embed_params else ""
return separator.join([query_string, current_embed_params])
return current_embed_params
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/commands/execution_control.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import os
import time
from collections.abc import Iterable, Mapping
from itertools import dropwhile
from pathlib import Path
from typing import TYPE_CHECKING, Literal, NoReturn
import streamlit as st
from streamlit.errors import NoSessionContext, StreamlitAPIException
from streamlit.file_util import get_main_script_directory, normalize_path_join
from streamlit.navigation.page import StreamlitPage
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner import (
RerunData,
ScriptRunContext,
get_script_run_ctx,
)
if TYPE_CHECKING:
from streamlit.runtime.state.query_params import QueryParams, QueryParamsInput
@gather_metrics("stop")
def stop() -> NoReturn: # type: ignore[misc]
"""Stops execution immediately.
Streamlit will not run any statements after `st.stop()`.
We recommend rendering a message to explain why the script has stopped.
Example
-------
>>> import streamlit as st
>>>
>>> name = st.text_input("Name")
>>> if not name:
>>> st.warning('Please input a name.')
>>> st.stop()
>>> st.success("Thank you for inputting a name.")
"""
ctx = get_script_run_ctx()
if ctx and ctx.script_requests:
ctx.script_requests.request_stop()
# Force a yield point so the runner can stop
st.empty()
def _new_fragment_id_queue(
ctx: ScriptRunContext,
scope: Literal["app", "fragment"],
) -> list[str]:
if scope == "app":
return []
# > scope == "fragment"
curr_queue = ctx.fragment_ids_this_run
# If st.rerun(scope="fragment") is called during a full script run, we raise an
# exception. This occurs, of course, if st.rerun(scope="fragment") is called
# outside of a fragment, but it somewhat surprisingly occurs if it gets called
# from within a fragment during a run of the full script. While this behavior may
# be surprising, it seems somewhat reasonable given that the correct behavior of
# calling st.rerun(scope="fragment") in this situation is unclear to me:
# * Rerunning just the fragment immediately may cause weirdness down the line
# as any part of the script that occurs after the fragment will not be
# executed.
# * Waiting until the full script run completes before rerunning the fragment
# seems odd (even if we normally do this before running a fragment not
# triggered by st.rerun()) because it defers the execution of st.rerun().
# * Rerunning the full app feels incorrect as we're seemingly ignoring the
# `scope` argument.
# With these issues and given that it seems pretty unnatural to have a
# fragment-scoped rerun happen during a full script run to begin with, it seems
# reasonable to just disallow this completely for now.
if not curr_queue:
raise StreamlitAPIException(
'scope="fragment" can only be specified from `@st.fragment`-decorated '
"functions during fragment reruns."
)
new_queue = list(dropwhile(lambda x: x != ctx.current_fragment_id, curr_queue))
if not new_queue:
raise RuntimeError(
"Could not find current_fragment_id in fragment_id_queue. This should never happen."
)
return new_queue
def _set_query_params_for_switch(
query_params_state: QueryParams,
new_query_params: QueryParamsInput | None,
) -> None:
"""Set query params for a switch page."""
if new_query_params is None:
query_params_state.clear()
return
if isinstance(new_query_params, Mapping) or (
isinstance(new_query_params, Iterable)
and not isinstance(
new_query_params, # type: ignore[unreachable]
(str, bytes),
)
):
query_params_state.from_dict(new_query_params)
return
raise StreamlitAPIException(
f"`query_params` must be a mapping or an iterable of (key, value) pairs not a `{type(new_query_params)}`."
)
@gather_metrics("rerun")
def rerun( # type: ignore[misc]
*, # The scope argument can only be passed via keyword.
scope: Literal["app", "fragment"] = "app",
) -> NoReturn: # ty: ignore[invalid-return-type]
"""Rerun the script immediately.
When ``st.rerun()`` is called, Streamlit halts the current script run and
executes no further statements. Streamlit immediately queues the script to
rerun.
When using ``st.rerun`` in a fragment, you can scope the rerun to the
fragment. However, if a fragment is running as part of a full-app rerun,
a fragment-scoped rerun is not allowed.
Parameters
----------
scope : "app" or "fragment"
Specifies what part of the app should rerun. If ``scope`` is ``"app"``
(default), the full app reruns. If ``scope`` is ``"fragment"``,
Streamlit only reruns the fragment from which this command is called.
Setting ``scope="fragment"`` is only valid inside a fragment during a
fragment rerun. If ``st.rerun(scope="fragment")`` is called during a
full-app rerun or outside of a fragment, Streamlit will raise a
``StreamlitAPIException``.
"""
if scope not in ["app", "fragment"]:
raise StreamlitAPIException(
f"'{scope}'is not a valid rerun scope. Valid scopes are 'app' and 'fragment'."
)
ctx = get_script_run_ctx()
if ctx and ctx.script_requests:
query_string = ctx.query_string
page_script_hash = ctx.page_script_hash
cached_message_hashes = ctx.cached_message_hashes
ctx.script_requests.request_rerun(
RerunData(
query_string=query_string,
page_script_hash=page_script_hash,
fragment_id_queue=_new_fragment_id_queue(ctx, scope),
is_fragment_scoped_rerun=scope == "fragment",
cached_message_hashes=cached_message_hashes,
context_info=ctx.context_info,
)
)
# Force a yield point so the runner can do the rerun
st.empty()
@gather_metrics("switch_page")
def switch_page( # type: ignore[misc]
page: str | Path | StreamlitPage,
*,
query_params: QueryParamsInput | None = None,
) -> NoReturn: # ty: ignore[invalid-return-type]
"""Programmatically switch the current page in a multipage app.
When ``st.switch_page`` is called, the current page execution stops and
the specified page runs as if the user clicked on it in the sidebar
navigation. The specified page must be recognized by Streamlit's multipage
architecture (your main Python file or a Python file in a ``pages/``
folder). Arbitrary Python scripts cannot be passed to ``st.switch_page``.
Parameters
----------
page : str, Path, or st.Page
The file path (relative to the main script) or an st.Page indicating
the page to switch to.
query_params : dict, list of tuples, or None
Query parameters to apply when navigating to the target page.
This can be a dictionary or an iterable of key-value tuples. Values can
be strings or iterables of strings (for repeated keys). When this is
``None`` (default), all non-embed query parameters are cleared during
navigation.
Examples
--------
**Example 1: Basic usage**
The following example shows how to switch to a different page in a
multipage app that uses the ``pages/`` directory:
.. code-block:: text
your-repository/
├── pages/
│ ├── page_1.py
│ └── page_2.py
└── your_app.py
>>> import streamlit as st
>>>
>>> if st.button("Home"):
>>> st.switch_page("your_app.py")
>>> if st.button("Page 1"):
>>> st.switch_page("pages/page_1.py")
>>> if st.button("Page 2"):
>>> st.switch_page("pages/page_2.py")
.. output::
https://doc-switch-page.streamlit.app/
height: 350px
**Example 2: Passing query parameters**
The following example shows how to pass query parameters when switching to a
different page. This example uses ``st.navigation`` to create a multipage app.
.. code-block:: text
your-repository/
├── page_2.py
└── your_app.py
>>> import streamlit as st
>>>
>>> def page_1():
>>> st.title("Page 1")
>>> if st.button("Switch to Page 2"):
>>> st.switch_page("page_2.py", query_params={"utm_source": "page_1"})
>>>
>>> pg = st.navigation([page_1, "page_2.py"])
>>> pg.run()
.. output::
https://doc-switch-page-query-params.streamlit.app/
height: 350px
"""
ctx = get_script_run_ctx()
if not ctx or not ctx.script_requests:
# This should never be the case
raise NoSessionContext()
page_script_hash = ""
if isinstance(page, StreamlitPage):
page_script_hash = page._script_hash
else:
# Convert Path to string if necessary
if isinstance(page, Path):
page = str(page)
main_script_directory = get_main_script_directory(ctx.main_script_path)
requested_page = os.path.realpath(
normalize_path_join(main_script_directory, page)
)
all_app_pages = ctx.pages_manager.get_pages().values()
matched_pages = [p for p in all_app_pages if p["script_path"] == requested_page]
if len(matched_pages) == 0:
raise StreamlitAPIException(
f"Could not find page: `{page}`. Must be the file path relative to the main script, "
f"from the directory: `{os.path.basename(main_script_directory)}`. Only the main app file "
"and files in the `pages/` directory are supported."
)
page_script_hash = matched_pages[0]["page_script_hash"]
# Reset query params (with exception of embed) and optionally apply overrides.
with ctx.session_state.query_params() as qp:
_set_query_params_for_switch(qp, query_params)
# Additional safeguard to ensure the query params
# are sent out to the frontend before the new rerun might clear
# outstanding messages. This uses the same time that is used as waiting
# in our event loop.
time.sleep(0.01)
ctx.script_requests.request_rerun(
RerunData(
query_string=ctx.query_string,
page_script_hash=page_script_hash,
cached_message_hashes=ctx.cached_message_hashes,
context_info=ctx.context_info,
)
)
# Force a yield point so the runner can do the rerun
st.empty()
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/commands/navigation.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from collections.abc import Callable, Mapping, Sequence
from pathlib import Path
from typing import TYPE_CHECKING, Literal, TypeAlias
from streamlit import config
from streamlit.errors import StreamlitAPIException
from streamlit.navigation.page import StreamlitPage
from streamlit.proto.ForwardMsg_pb2 import ForwardMsg
from streamlit.proto.Navigation_pb2 import Navigation as NavigationProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.pages_manager import PagesManager
from streamlit.runtime.scriptrunner_utils.script_run_context import (
ScriptRunContext,
get_script_run_ctx,
)
from streamlit.string_util import is_emoji
if TYPE_CHECKING:
from streamlit.source_util import PageHash, PageInfo
SectionHeader: TypeAlias = str
PageType: TypeAlias = str | Path | Callable[[], None] | StreamlitPage
def convert_to_streamlit_page(
page_input: PageType,
) -> StreamlitPage:
"""Convert various input types to StreamlitPage objects."""
if isinstance(page_input, StreamlitPage):
return page_input
if isinstance(page_input, str):
return StreamlitPage(page_input)
if isinstance(page_input, Path):
return StreamlitPage(page_input)
if callable(page_input):
# Convert function to StreamlitPage
return StreamlitPage(page_input)
raise StreamlitAPIException(
f"Invalid page type: {type(page_input)}. Must be either a string path, "
"a pathlib.Path, a callable function, or a st.Page object."
)
def pages_from_nav_sections(
nav_sections: dict[SectionHeader, list[StreamlitPage]],
) -> list[StreamlitPage]:
page_list = []
for pages in nav_sections.values():
page_list.extend(pages.copy())
return page_list
def send_page_not_found(ctx: ScriptRunContext) -> None:
msg = ForwardMsg()
msg.page_not_found.page_name = ""
ctx.enqueue(msg)
@gather_metrics("navigation")
def navigation(
pages: Sequence[PageType] | Mapping[SectionHeader, Sequence[PageType]],
*,
position: Literal["sidebar", "hidden", "top"] = "sidebar",
expanded: bool = False,
) -> StreamlitPage:
"""
Configure the available pages in a multipage app.
Call ``st.navigation`` in your entrypoint file to define the available
pages for your app. ``st.navigation`` returns the current page, which can
be executed using ``.run()`` method.
When using ``st.navigation``, your entrypoint file (the file passed to
``streamlit run``) acts like a router or frame of common elements around
each of your pages. Streamlit executes the entrypoint file with every app
rerun. To execute the current page, you must call the ``.run()`` method on
the ``StreamlitPage`` object returned by ``st.navigation``.
The set of available pages can be updated with each rerun for dynamic
navigation. By default, ``st.navigation`` displays the available pages in
the sidebar if there is more than one page. This behavior can be changed
using the ``position`` keyword argument.
As soon as any session of your app executes the ``st.navigation`` command,
your app will ignore the ``pages/`` directory (across all sessions).
Parameters
----------
pages : Sequence[page-like], Mapping[str, Sequence[page-like]]
The available pages for the app.
To create a navigation menu with no sections or page groupings,
``pages`` must be a list of page-like objects. Page-like objects are
anything that can be passed to ``st.Page`` or a ``StreamlitPage``
object returned by ``st.Page``.
To create labeled sections or page groupings within the navigation
menu, ``pages`` must be a dictionary. Each key is the label of a
section and each value is the list of page-like objects for
that section. If you use ``position="top"``, each grouping will be a
collapsible item in the navigation menu. For top navigation, if you use
an empty string as a section header, the pages in that section will be
displayed at the beginning of the menu before the collapsible sections.
When you use a string or path as a page-like object, they are
internally passed to ``st.Page`` and converted to ``StreamlitPage``
objects. In this case, the page will have the default title, icon, and
path inferred from its path or filename. To customize these attributes
for your page, initialize your page with ``st.Page``.
position : "sidebar", "top", or "hidden"
The position of the navigation menu. If this is ``"sidebar"``
(default), the navigation widget appears at the top of the sidebar. If
this is ``"top"``, the navigation appears in the top header of the app.
If this is ``"hidden"``, the navigation widget is not displayed.
If there is only one page in ``pages``, the navigation will be hidden
for any value of ``position``.
expanded : bool
Whether the navigation menu should be expanded. If this is ``False``
(default), the navigation menu will be collapsed and will include a
button to view more options when there are too many pages to display.
If this is ``True``, the navigation menu will always be expanded; no
button to collapse the menu will be displayed.
If ``st.navigation`` changes from ``expanded=True`` to
``expanded=False`` on a rerun, the menu will stay expanded and a
collapse button will be displayed.
The parameter is only used when ``position="sidebar"``.
Returns
-------
StreamlitPage
The current page selected by the user. To run the page, you must use
the ``.run()`` method on it.
Examples
--------
The following examples show different possible entrypoint files, each named
``streamlit_app.py``. An entrypoint file is passed to ``streamlit run``. It
manages your app's navigation and serves as a router between pages.
**Example 1: Use a callable or Python file as a page**
You can declare pages from callables or file paths. If you pass callables
or paths to ``st.navigation`` as a page-like objects, they are internally
converted to ``StreamlitPage`` objects using ``st.Page``. In this case, the
page titles, icons, and paths are inferred from the file or callable names.
``page_1.py`` (in the same directory as your entrypoint file):
>>> import streamlit as st
>>>
>>> st.title("Page 1")
``streamlit_app.py``:
>>> import streamlit as st
>>>
>>> def page_2():
... st.title("Page 2")
>>>
>>> pg = st.navigation(["page_1.py", page_2])
>>> pg.run()
.. output::
https://doc-navigation-example-1.streamlit.app/
height: 200px
**Example 2: Group pages into sections and customize them with ``st.Page``**
You can use a dictionary to create sections within your navigation menu. In
the following example, each page is similar to Page 1 in Example 1, and all
pages are in the same directory. However, you can use Python files from
anywhere in your repository. ``st.Page`` is used to give each page a custom
title. For more information, see |st.Page|_.
Directory structure:
>>> your_repository/
>>> ├── create_account.py
>>> ├── learn.py
>>> ├── manage_account.py
>>> ├── streamlit_app.py
>>> └── trial.py
``streamlit_app.py``:
>>> import streamlit as st
>>>
>>> pages = {
... "Your account": [
... st.Page("create_account.py", title="Create your account"),
... st.Page("manage_account.py", title="Manage your account"),
... ],
... "Resources": [
... st.Page("learn.py", title="Learn about us"),
... st.Page("trial.py", title="Try it out"),
... ],
... }
>>>
>>> pg = st.navigation(pages)
>>> pg.run()
.. output::
https://doc-navigation-example-2.streamlit.app/
height: 300px
**Example 3: Use top navigation**
You can use the ``position`` parameter to place the navigation at the top
of the app. This is useful for apps with a lot of pages because it allows
you to create collapsible sections for each group of pages. The following
example uses the same directory structure as Example 2 and shows how to
create a top navigation menu.
``streamlit_app.py``:
>>> import streamlit as st
>>>
>>> pages = {
... "Your account": [
... st.Page("create_account.py", title="Create your account"),
... st.Page("manage_account.py", title="Manage your account"),
... ],
... "Resources": [
... st.Page("learn.py", title="Learn about us"),
... st.Page("trial.py", title="Try it out"),
... ],
... }
>>>
>>> pg = st.navigation(pages, position="top")
>>> pg.run()
.. output::
https://doc-navigation-top.streamlit.app/
height: 300px
**Example 4: Stateful widgets across multiple pages**
Call widget functions in your entrypoint file when you want a widget to be
stateful across pages. Assign keys to your common widgets and access their
values through Session State within your pages.
``streamlit_app.py``:
>>> import streamlit as st
>>>
>>> def page1():
>>> st.write(st.session_state.foo)
>>>
>>> def page2():
>>> st.write(st.session_state.bar)
>>>
>>> # Widgets shared by all the pages
>>> st.sidebar.selectbox("Foo", ["A", "B", "C"], key="foo")
>>> st.sidebar.checkbox("Bar", key="bar")
>>>
>>> pg = st.navigation([page1, page2])
>>> pg.run()
.. output::
https://doc-navigation-multipage-widgets.streamlit.app/
height: 350px
.. |st.Page| replace:: ``st.Page``
.. _st.Page: https://docs.streamlit.io/develop/api-reference/navigation/st.page
"""
# Validate position parameter
if not isinstance(position, str) or position not in ["sidebar", "hidden", "top"]:
raise StreamlitAPIException(
f'Invalid position "{position}". '
'The position parameter must be one of "sidebar", "hidden", or "top".'
)
# Disable the use of the pages feature (ie disregard v1 behavior of Multipage Apps)
PagesManager.uses_pages_directory = False
return _navigation(pages, position=position, expanded=expanded)
def _navigation(
pages: Sequence[PageType] | Mapping[SectionHeader, Sequence[PageType]],
*,
position: Literal["sidebar", "hidden", "top"],
expanded: bool,
) -> StreamlitPage:
if isinstance(pages, Sequence):
converted_pages = [convert_to_streamlit_page(p) for p in pages]
nav_sections = {"": converted_pages}
else:
nav_sections = {
section: [convert_to_streamlit_page(p) for p in section_pages]
for section, section_pages in pages.items()
}
page_list = pages_from_nav_sections(nav_sections)
if not page_list:
raise StreamlitAPIException(
"`st.navigation` must be called with at least one `st.Page`."
)
default_page = None
pagehash_to_pageinfo: dict[PageHash, PageInfo] = {}
# Get the default page.
for section_header in nav_sections:
for page in nav_sections[section_header]:
if page._default:
if default_page is not None:
raise StreamlitAPIException(
"Multiple Pages specified with `default=True`. "
"At most one Page can be set to default."
)
default_page = page
if default_page is None:
default_page = page_list[0]
default_page._default = True
ctx = get_script_run_ctx()
if not ctx:
# This should never run in Streamlit, but we want to make sure that
# the function always returns a page
default_page._can_be_called = True
return default_page
# Build the pagehash-to-pageinfo mapping.
for section_header in nav_sections:
for page in nav_sections[section_header]:
script_path = str(page._page) if isinstance(page._page, Path) else ""
script_hash = page._script_hash
if script_hash in pagehash_to_pageinfo:
# The page script hash is solely based on the url path
# So duplicate page script hashes are due to duplicate url paths
raise StreamlitAPIException(
f"Multiple Pages specified with URL pathname {page.url_path}. "
"URL pathnames must be unique. The url pathname may be "
"inferred from the filename, callable name, or title."
)
pagehash_to_pageinfo[script_hash] = {
"page_script_hash": script_hash,
"page_name": page.title,
"icon": page.icon,
"script_path": script_path,
"url_pathname": page.url_path,
}
msg = ForwardMsg()
# Handle position logic correctly
if position == "hidden":
msg.navigation.position = NavigationProto.Position.HIDDEN
elif position == "top":
msg.navigation.position = NavigationProto.Position.TOP
elif position == "sidebar":
# Only apply config override if position is sidebar
if config.get_option("client.showSidebarNavigation") is False:
msg.navigation.position = NavigationProto.Position.HIDDEN
else:
msg.navigation.position = NavigationProto.Position.SIDEBAR
msg.navigation.expanded = expanded
msg.navigation.sections[:] = nav_sections.keys()
for section_header in nav_sections:
for page in nav_sections[section_header]:
p = msg.navigation.app_pages.add()
p.page_script_hash = page._script_hash
p.page_name = page.title
p.icon = f"emoji:{page.icon}" if is_emoji(page.icon) else page.icon
p.is_default = page._default
p.section_header = section_header
p.url_pathname = page.url_path
# Inform our page manager about the set of pages we have
ctx.pages_manager.set_pages(pagehash_to_pageinfo)
found_page = ctx.pages_manager.get_page_script(
fallback_page_hash=default_page._script_hash
)
page_to_return = None
if found_page:
found_page_script_hash = found_page["page_script_hash"]
matching_pages = [
p for p in page_list if p._script_hash == found_page_script_hash
]
if len(matching_pages) > 0:
page_to_return = matching_pages[0]
if not page_to_return:
send_page_not_found(ctx)
page_to_return = default_page
# Ordain the page that can be called
page_to_return._can_be_called = True
msg.navigation.page_script_hash = page_to_return._script_hash
# Set the current page script hash to the page that is going to be executed
ctx.set_mpa_v2_page(page_to_return._script_hash)
# This will either navigation or yield if the page is not found
ctx.enqueue(msg)
return page_to_return
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/commands/echo.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import ast
import contextlib
import re
import textwrap
import traceback
from typing import TYPE_CHECKING, Any, Literal, cast
from streamlit.runtime.metrics_util import gather_metrics
if TYPE_CHECKING:
from collections.abc import Generator, Iterable
_SPACES_RE = re.compile("\\s*")
_EMPTY_LINE_RE = re.compile("\\s*\n")
@gather_metrics("echo")
@contextlib.contextmanager
def echo(
code_location: Literal["above", "below"] = "above",
) -> Generator[None, None, None]:
"""Use in a `with` block to draw some code on the app, then execute it.
Parameters
----------
code_location : "above" or "below"
Whether to show the echoed code before or after the results of the
executed code block.
Example
-------
>>> import streamlit as st
>>>
>>> with st.echo():
>>> st.write('This code will be printed')
"""
from streamlit import code, empty, source_util, warning
if code_location == "below":
show_code = code
show_warning = warning
else:
placeholder = empty()
show_code = placeholder.code
show_warning = placeholder.warning
try:
# Get stack frame *before* running the echoed code. The frame's
# line number will point to the `st.echo` statement we're running.
frame = traceback.extract_stack()[-3]
filename, start_line = frame.filename, frame.lineno or 0
# Read the file containing the source code of the echoed statement.
with source_util.open_python_file(filename) as source_file:
source_lines = source_file.readlines()
# Use ast to parse the Python file and find the code block to display
root_node = ast.parse("".join(source_lines))
line_to_node_map: dict[int, Any] = {}
def collect_body_statements(node: ast.AST) -> None:
if not hasattr(node, "body"):
return
for child in ast.iter_child_nodes(node):
# If child doesn't have "lineno", it is not something we could display
if hasattr(child, "lineno"):
line_to_node_map[cast("int", child.lineno)] = child
collect_body_statements(child)
collect_body_statements(root_node)
# In AST module the lineno (line numbers) are 1-indexed,
# so we decrease it by 1 to lookup in source lines list
echo_block_start_line = line_to_node_map[start_line].body[0].lineno - 1
echo_block_end_line = line_to_node_map[start_line].end_lineno
lines_to_display = source_lines[echo_block_start_line:echo_block_end_line]
code_string = textwrap.dedent("".join(lines_to_display))
# Run the echoed code...
yield
# And draw the code string to the app!
show_code(code_string, "python")
except FileNotFoundError as err:
show_warning(f"Unable to display code. {err}")
def _get_initial_indent(lines: Iterable[str]) -> int:
"""Return the indent of the first non-empty line in the list.
If all lines are empty, return 0.
"""
for line in lines:
indent = _get_indent(line)
if indent is not None:
return indent
return 0
def _get_indent(line: str) -> int | None:
"""Get the number of whitespaces at the beginning of the given line.
If the line is empty, or if it contains just whitespace and a newline,
return None.
"""
if _EMPTY_LINE_RE.match(line) is not None:
return None
match = _SPACES_RE.match(line)
return match.end() if match is not None else 0
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/commands/logo.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
"""Handle App logos."""
from __future__ import annotations
from typing import Literal
from streamlit import url_util
from streamlit.elements.lib.image_utils import AtomicImage, image_to_url
from streamlit.elements.lib.layout_utils import LayoutConfig
from streamlit.errors import StreamlitAPIException
from streamlit.proto.ForwardMsg_pb2 import ForwardMsg
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner_utils.script_run_context import get_script_run_ctx
def _invalid_logo_text(field_name: str) -> str:
return (
f"The {field_name} passed to st.logo is invalid - See "
"[documentation](https://docs.streamlit.io/develop/api-reference/media/st.logo) "
"for more information on valid types"
)
@gather_metrics("logo")
def logo(
image: AtomicImage,
*, # keyword-only args:
size: Literal["small", "medium", "large"] = "medium",
link: str | None = None,
icon_image: AtomicImage | None = None,
) -> None:
r"""
Renders a logo in the upper-left corner of your app and its sidebar.
If ``st.logo`` is called multiple times within a page, Streamlit will
render the image passed in the last call. For the most consistent results,
call ``st.logo`` early in your page script and choose an image that works
well in both light and dark mode. Avoid empty margins around your image.
If your logo does not work well for both light and dark mode, consider
setting the theme and hiding the settings menu from users with the
`configuration option <https://docs.streamlit.io/develop/api-reference/configuration/config.toml>`_
``client.toolbarMode="minimal"``.
Parameters
----------
image: Anything supported by st.image (except list)
The image to display in the upper-left corner of your app and its
sidebar. This can be any of the types supported by |st.image|_ except
a list. If ``icon_image`` is also provided, then Streamlit will only
display ``image`` in the sidebar.
Streamlit scales the image to a max height set by ``size`` and a max
width to fit within the sidebar.
.. |st.image| replace:: ``st.image``
.. _st.image: https://docs.streamlit.io/develop/api-reference/media/st.image
size: "small", "medium", or "large"
The size of the image displayed in the upper-left corner of the app and its
sidebar. The possible values are as follows:
- ``"small"``: 20px max height
- ``"medium"`` (default): 24px max height
- ``"large"``: 32px max height
link : str or None
The external URL to open when a user clicks on the logo. The URL must
start with "\http://" or "\https://". If ``link`` is ``None`` (default),
the logo will not include a hyperlink.
icon_image: Anything supported by st.image (except list) or None
An optional, typically smaller image to replace ``image`` in the
upper-left corner when the sidebar is closed. This can be any of the
types supported by ``st.image`` except a list. If ``icon_image`` is
``None`` (default), Streamlit will always display ``image`` in the
upper-left corner, regardless of whether the sidebar is open or closed.
Otherwise, Streamlit will render ``icon_image`` in the upper-left
corner of the app when the sidebar is closed.
Streamlit scales the image to a max height set by ``size`` and a max
width to fit within the sidebar. If the sidebar is closed, the max
width is retained from when it was last open.
For best results, pass a wide or horizontal image to ``image`` and a
square image to ``icon_image``. Or, pass a square image to ``image``
and leave ``icon_image=None``.
Examples
--------
A common design practice is to use a wider logo in the sidebar, and a
smaller, icon-styled logo in your app's main body.
>>> import streamlit as st
>>>
>>> st.logo(
... LOGO_URL_LARGE,
... link="https://streamlit.io/gallery",
... icon_image=LOGO_URL_SMALL,
... )
Try switching logos around in the following example:
>>> import streamlit as st
>>>
>>> HORIZONTAL_RED = "images/horizontal_red.png"
>>> ICON_RED = "images/icon_red.png"
>>> HORIZONTAL_BLUE = "images/horizontal_blue.png"
>>> ICON_BLUE = "images/icon_blue.png"
>>>
>>> options = [HORIZONTAL_RED, ICON_RED, HORIZONTAL_BLUE, ICON_BLUE]
>>> sidebar_logo = st.selectbox("Sidebar logo", options, 0)
>>> main_body_logo = st.selectbox("Main body logo", options, 1)
>>>
>>> st.logo(sidebar_logo, icon_image=main_body_logo)
>>> st.sidebar.markdown("Hi!")
.. output::
https://doc-logo.streamlit.app/
height: 300px
"""
ctx = get_script_run_ctx()
if ctx is None:
return
fwd_msg = ForwardMsg()
try:
image_url = image_to_url(
image,
layout_config=LayoutConfig(width="content"),
clamp=False,
channels="RGB",
output_format="auto",
image_id="logo",
)
fwd_msg.logo.image = image_url
except Exception as ex:
raise StreamlitAPIException(_invalid_logo_text("image")) from ex
if link:
# Handle external links:
if url_util.is_url(link, ("http", "https")):
fwd_msg.logo.link = link
else:
raise StreamlitAPIException(
f"Invalid link: {link} - the link param supports external links only and must "
f"start with either http:// or https://."
)
if icon_image:
try:
icon_image_url = image_to_url(
icon_image,
layout_config=LayoutConfig(width="content"),
clamp=False,
channels="RGB",
output_format="auto",
image_id="icon-image",
)
fwd_msg.logo.icon_image = icon_image_url
except Exception as ex:
raise StreamlitAPIException(_invalid_logo_text("icon_image")) from ex
def validate_size(size: str) -> str:
if isinstance(size, str):
image_size = size.lower()
valid_sizes = ["small", "medium", "large"]
if image_size in valid_sizes:
return image_size
raise StreamlitAPIException(
f'The size argument to st.logo must be "small", "medium", or "large". \n'
f"The argument passed was {size}."
)
fwd_msg.logo.size = validate_size(size)
ctx.enqueue(fwd_msg)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/commands/page_config.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import random
from collections.abc import Mapping
from pathlib import Path
from textwrap import dedent
from typing import TYPE_CHECKING, Any, Final, Literal, TypeAlias, cast
from streamlit.elements.lib.image_utils import AtomicImage, image_to_url
from streamlit.elements.lib.layout_utils import LayoutConfig
from streamlit.errors import (
StreamlitInvalidMenuItemKeyError,
StreamlitInvalidPageLayoutError,
StreamlitInvalidSidebarStateError,
StreamlitInvalidURLError,
)
from streamlit.proto.ForwardMsg_pb2 import ForwardMsg as ForwardProto
from streamlit.proto.PageConfig_pb2 import PageConfig as PageConfigProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner_utils.script_run_context import get_script_run_ctx
from streamlit.string_util import is_emoji, validate_material_icon
from streamlit.url_util import is_url
if TYPE_CHECKING:
from typing import TypeGuard
GET_HELP_KEY: Final = "get help"
REPORT_A_BUG_KEY: Final = "report a bug"
ABOUT_KEY: Final = "about"
PageIcon: TypeAlias = AtomicImage | str
Layout: TypeAlias = Literal["centered", "wide"]
InitialSideBarState: TypeAlias = Literal["auto", "expanded", "collapsed"] | int
_GetHelp: TypeAlias = Literal["Get help", "Get Help", "get help"]
_ReportABug: TypeAlias = Literal["Report a bug", "report a bug"]
_About: TypeAlias = Literal["About", "about"]
MenuKey: TypeAlias = Literal[_GetHelp, _ReportABug, _About]
MenuItems: TypeAlias = Mapping[MenuKey, str | None]
RANDOM_EMOJIS: Final = list(
"🔥™🎉🚀🌌💣✨🌙🎆🎇💥🤩🤙🌛🤘⬆💡🤪🥂⚡💨🌠🎊🍿😛🔮🤟🌃🍃🍾💫▪🌴🎈🎬🌀🎄😝☔⛽🍂💃😎🍸🎨🥳☀😍🅱🌞😻🌟😜💦💅🦄😋😉👻🍁🤤👯🌻‼🌈👌🎃💛😚🔫🙌👽🍬🌅☁🍷👭☕🌚💁👅🥰🍜😌🎥🕺❕🧡☄💕🍻✅🌸🚬🤓🍹®☺💪😙☘🤠✊🤗🍵🤞😂💯😏📻🎂💗💜🌊❣🌝😘💆🤑🌿🦋😈⛄🚿😊🌹🥴😽💋😭🖤🙆👐⚪💟☃🙈🍭💻🥀🚗🤧🍝💎💓🤝💄💖🔞⁉⏰🕊🎧☠♥🌳🏾🙉⭐💊🍳🌎🙊💸❤🔪😆🌾✈📚💀🏠✌🏃🌵🚨💂🤫🤭😗😄🍒👏🙃🖖💞😅🎅🍄🆓👉💩🔊🤷⌚👸😇🚮💏👳🏽💘💿💉👠🎼🎶🎤👗❄🔐🎵🤒🍰👓🏄🌲🎮🙂📈🚙📍😵🗣❗🌺🙄👄🚘🥺🌍🏡♦💍🌱👑👙☑👾🍩🥶📣🏼🤣☯👵🍫➡🎀😃✋🍞🙇😹🙏👼🐝⚫🎁🍪🔨🌼👆👀😳🌏📖👃🎸👧💇🔒💙😞⛅🏻🍴😼🗿🍗♠🦁✔🤖☮🐢🐎💤😀🍺😁😴📺☹😲👍🎭💚🍆🍋🔵🏁🔴🔔🧐👰☎🏆🤡🐠📲🙋📌🐬✍🔑📱💰🐱💧🎓🍕👟🐣👫🍑😸🍦👁🆗🎯📢🚶🦅🐧💢🏀🚫💑🐟🌽🏊🍟💝💲🐍🍥🐸☝♣👊⚓❌🐯🏈📰🌧👿🐳💷🐺📞🆒🍀🤐🚲🍔👹🙍🌷🙎🐥💵🔝📸⚠❓🎩✂🍼😑⬇⚾🍎💔🐔⚽💭🏌🐷🍍✖🍇📝🍊🐙👋🤔🥊🗽🐑🐘🐰💐🐴♀🐦🍓✏👂🏴👇🆘😡🏉👩💌😺✝🐼🐒🐶👺🖕👬🍉🐻🐾⬅⏬▶👮🍌♂🔸👶🐮👪⛳🐐🎾🐕👴🐨🐊🔹©🎣👦👣👨👈💬⭕📹📷"
)
def _lower_clean_dict_keys(dict: MenuItems) -> dict[str, Any]:
return {str(k).lower().strip(): v for k, v in dict.items()}
def _get_favicon_string(page_icon: PageIcon) -> str:
"""Return the string to pass to the frontend to have it show
the given PageIcon.
If page_icon is a string that looks like an emoji (or an emoji shortcode),
we return it as-is. Otherwise we use `image_to_url` to return a URL.
(If `image_to_url` raises an error and page_icon is a string, return
the unmodified page_icon string instead of re-raising the error.)
"""
# Choose a random emoji.
if page_icon == "random":
return get_random_emoji()
# If page_icon is an emoji, return it as is.
if isinstance(page_icon, str) and is_emoji(page_icon):
return f"emoji:{page_icon}"
if isinstance(page_icon, str) and page_icon.startswith(":material"):
return validate_material_icon(page_icon)
# Convert Path to string if necessary
if isinstance(page_icon, Path):
page_icon = str(page_icon)
# Fall back to image_to_url.
try:
return image_to_url(
page_icon,
layout_config=LayoutConfig(
width="stretch"
), # Always use full width for favicons
clamp=False,
channels="RGB",
output_format="auto",
image_id="favicon",
)
except Exception:
if isinstance(page_icon, str):
# This fall-thru handles emoji shortcode strings (e.g. ":shark:"),
# which aren't valid filenames and so will cause an Exception from
# `image_to_url`.
return page_icon
raise
@gather_metrics("set_page_config")
def set_page_config(
page_title: str | None = None,
page_icon: PageIcon | None = None,
layout: Layout | None = None,
initial_sidebar_state: InitialSideBarState | None = None,
menu_items: MenuItems | None = None,
) -> None:
"""
Configure the default settings of the page.
This command can be called multiple times in a script run to dynamically
change the page configuration. The calls are additive, with each successive
call overriding only the parameters that are specified.
Parameters
----------
page_title: str or None
The page title, shown in the browser tab. If this is ``None``
(default), the page title is inherited from the previous call of
``st.set_page_config``. If this is ``None`` and no previous call
exists, the page title is inferred from the page source.
If a page source is a Python file, its inferred title is derived from
the filename. If a page source is a callable object, its inferred title
is derived from the callable's name.
page_icon : Anything supported by st.image (except list), str, or None
The page favicon. If ``page_icon`` is ``None`` (default), the page icon
is inherited from the previous call of ``st.set_page_config``. If this
is ``None`` and no previous call exists, the favicon is a monochrome
Streamlit logo.
In addition to the types supported by |st.image|_ (except list), the
following strings are valid:
- A single-character emoji. For example, you can set ``page_icon="🦈"``.
- An emoji short code. For example, you can set ``page_icon=":shark:"``.
For a list of all supported codes, see
https://share.streamlit.io/streamlit/emoji-shortcodes.
- The string literal, ``"random"``. You can set ``page_icon="random"``
to set a random emoji from the supported list above.
- An icon from the Material Symbols library (rounded style) in the
format ``":material/icon_name:"`` where "icon_name" is the name
of the icon in snake case.
For example, ``page_icon=":material/thumb_up:"`` will display the
Thumb Up icon. Find additional icons in the `Material Symbols \
<https://fonts.google.com/icons?icon.set=Material+Symbols&icon.style=Rounded>`_
font library.
.. note::
Colors are not supported for Material icons. When you use a
Material icon for favicon, it will be black, regardless of browser
theme.
.. |st.image| replace:: ``st.image``
.. _st.image: https://docs.streamlit.io/develop/api-reference/media/st.image
layout: "centered", "wide", or None
How the page content should be laid out. If this is ``None`` (default),
the page layout is inherited from the previous call of
``st.set_page_config``. If this is ``None`` and no previous call
exists, the page layout is ``"centered"``.
``"centered"`` constrains the elements into a centered column of fixed
width. ``"wide"`` uses the entire screen.
initial_sidebar_state: "auto", "expanded", "collapsed", int, or None
How the sidebar should start out. If this is ``None`` (default), the
sidebar state is inherited from the previous call of
``st.set_page_config``. If no previous call exists, the sidebar state
is ``"auto"``.
The following states are supported:
- ``"auto"``: The sidebar is hidden on small devices and shown otherwise.
- ``"expanded"``: The sidebar is shown initially.
- ``"collapsed"``: The sidebar is hidden initially.
- ``int``: Set the initial sidebar width in pixels. The sidebar will use
"auto" behavior but start with the specified width. Must be a positive integer.
The width is limited to a minimum of 200px and a maximum of 600px.
In most cases, ``"auto"`` provides the best user experience across
devices of different sizes.
menu_items: dict
Configure the menu that appears on the top-right side of this app.
The keys in this dict denote the menu item to configure. The following
keys can have string or ``None`` values:
- "Get help": The URL this menu item should point to.
- "Report a Bug": The URL this menu item should point to.
- "About": A markdown string to show in the About dialog.
A URL may also refer to an email address e.g. ``mailto:john@example.com``.
If you do not include a key, its menu item will be hidden (unless it
was set by a previous call to ``st.set_page_config``). To remove an
item that was specified in a previous call to ``st.set_page_config``,
set its value to ``None`` in the dictionary.
Example
-------
>>> import streamlit as st
>>>
>>> st.set_page_config(
... page_title="Ex-stream-ly Cool App",
... page_icon="🧊",
... layout="wide",
... initial_sidebar_state="expanded",
... menu_items={
... 'Get Help': 'https://www.extremelycoolapp.com/help',
... 'Report a bug': "https://www.extremelycoolapp.com/bug",
... 'About': "# This is a header. This is an *extremely* cool app!"
... }
... )
"""
msg = ForwardProto()
if page_title is not None:
msg.page_config_changed.title = page_title
if page_icon is not None:
msg.page_config_changed.favicon = _get_favicon_string(page_icon)
pb_layout: PageConfigProto.Layout.ValueType
if layout == "centered":
pb_layout = PageConfigProto.CENTERED
elif layout == "wide":
pb_layout = PageConfigProto.WIDE
elif layout is None:
# Allows for multiple (additive) calls to set_page_config
pb_layout = PageConfigProto.LAYOUT_UNSET
else:
# Note: Pylance incorrectly notes this error as unreachable
raise StreamlitInvalidPageLayoutError(layout=layout)
msg.page_config_changed.layout = pb_layout
pb_sidebar_state: PageConfigProto.SidebarState.ValueType
if initial_sidebar_state == "auto":
pb_sidebar_state = PageConfigProto.AUTO
elif initial_sidebar_state == "expanded":
pb_sidebar_state = PageConfigProto.EXPANDED
elif initial_sidebar_state == "collapsed":
pb_sidebar_state = PageConfigProto.COLLAPSED
elif initial_sidebar_state is None:
# Allows for multiple (additive) calls to set_page_config
pb_sidebar_state = PageConfigProto.SIDEBAR_UNSET
elif isinstance(initial_sidebar_state, int):
# Integer values set the sidebar width and use AUTO state
if initial_sidebar_state <= 0:
raise StreamlitInvalidSidebarStateError(
initial_sidebar_state=f"width must be positive (got {initial_sidebar_state})"
)
pb_sidebar_state = PageConfigProto.AUTO
msg.page_config_changed.initial_sidebar_width.pixel_width = (
initial_sidebar_state
)
else:
# Note: Pylance incorrectly notes this error as unreachable
raise StreamlitInvalidSidebarStateError(
initial_sidebar_state=initial_sidebar_state
)
msg.page_config_changed.initial_sidebar_state = pb_sidebar_state
if menu_items is not None:
lowercase_menu_items = cast("MenuItems", _lower_clean_dict_keys(menu_items))
validate_menu_items(lowercase_menu_items)
menu_items_proto = msg.page_config_changed.menu_items
set_menu_items_proto(lowercase_menu_items, menu_items_proto)
ctx = get_script_run_ctx()
if ctx is None:
return
ctx.enqueue(msg)
def get_random_emoji() -> str:
# TODO: fix the random seed with a hash of the user's app code, for stability?
return random.choice(RANDOM_EMOJIS) # noqa: S311
def set_menu_items_proto(
lowercase_menu_items: MenuItems, menu_items_proto: PageConfigProto.MenuItems
) -> None:
if GET_HELP_KEY in lowercase_menu_items:
if lowercase_menu_items[GET_HELP_KEY] is not None:
menu_items_proto.get_help_url = lowercase_menu_items[GET_HELP_KEY]
else:
menu_items_proto.hide_get_help = True
if REPORT_A_BUG_KEY in lowercase_menu_items:
if lowercase_menu_items[REPORT_A_BUG_KEY] is not None:
menu_items_proto.report_a_bug_url = lowercase_menu_items[REPORT_A_BUG_KEY]
else:
menu_items_proto.hide_report_a_bug = True
if ABOUT_KEY in lowercase_menu_items:
if lowercase_menu_items[ABOUT_KEY] is not None:
menu_items_proto.about_section_md = dedent(
lowercase_menu_items[ABOUT_KEY] or ""
)
else:
# For multiple calls to set_page_config, clears previously set about markdown
menu_items_proto.clear_about_md = True
def validate_menu_items(menu_items: MenuItems) -> None:
for k, v in menu_items.items():
if not valid_menu_item_key(k):
raise StreamlitInvalidMenuItemKeyError(key=k)
if v is not None and (
not is_url(v, ("http", "https", "mailto")) and k != ABOUT_KEY
):
raise StreamlitInvalidURLError(url=v)
def valid_menu_item_key(key: str) -> TypeGuard[MenuKey]:
return key in {GET_HELP_KEY, REPORT_A_BUG_KEY, ABOUT_KEY}
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/web/__init__.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/web/cache_storage_manager_config.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from typing import TYPE_CHECKING
from streamlit.runtime.caching.storage.local_disk_cache_storage import (
LocalDiskCacheStorageManager,
)
if TYPE_CHECKING:
from streamlit.runtime.caching.storage import CacheStorageManager
def create_default_cache_storage_manager() -> CacheStorageManager:
"""
Get the cache storage manager.
It would be used both in server.py and in cli.py to have unified cache storage.
Returns
-------
CacheStorageManager
The cache storage manager.
"""
return LocalDiskCacheStorageManager()
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/web/bootstrap.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import asyncio
import os
import signal
import sys
from typing import Any, Final
from streamlit import cli_util, config, env_util, file_util, net_util, secrets
from streamlit.logger import get_logger
from streamlit.watcher import report_watchdog_availability, watch_file
from streamlit.web.server import Server, server_address_is_unix_socket, server_util
_LOGGER: Final = get_logger(__name__)
# The maximum possible total size of a static directory.
# We agreed on these limitations for the initial release of static file sharing,
# based on security concerns from the SiS and Community Cloud teams
MAX_APP_STATIC_FOLDER_SIZE = 1 * 1024 * 1024 * 1024 # 1 GB
def _set_up_signal_handler(server: Server) -> None:
_LOGGER.debug("Setting up signal handler")
def signal_handler(signal_number: int, stack_frame: Any) -> None: # noqa: ARG001
# The server will shut down its threads and exit its loop.
server.stop()
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
if sys.platform == "win32":
signal.signal(signal.SIGBREAK, signal_handler)
else:
signal.signal(signal.SIGQUIT, signal_handler)
def _fix_sys_path(main_script_path: str) -> None:
"""Add the script's folder to the sys path.
Python normally does this automatically, but since we exec the script
ourselves we need to do it instead.
"""
sys.path.insert(0, os.path.dirname(main_script_path))
def _maybe_install_uvloop(running_in_event_loop: bool) -> None:
"""Install uvloop as the default event loop policy if available."""
if running_in_event_loop:
return
if env_util.IS_WINDOWS:
return
try:
import uvloop
except ModuleNotFoundError:
return
try:
uvloop.install()
_LOGGER.debug("uvloop installed as default event loop policy.")
except Exception:
_LOGGER.warning(
"Failed to install uvloop. Falling back to default loop.", exc_info=True
)
def _fix_tornado_crash() -> None:
"""Set default asyncio policy to be compatible with Tornado 6.
Tornado 6 (at least) is not compatible with the default
asyncio implementation on Windows. So here we
pick the older SelectorEventLoopPolicy when the OS is Windows
if the known-incompatible default policy is in use.
This has to happen as early as possible to make it a low priority and
overridable
See: https://github.com/tornadoweb/tornado/issues/2608
FIXME: if/when tornado supports the defaults in asyncio,
remove and bump tornado requirement for py38
"""
if env_util.IS_WINDOWS:
try:
from asyncio import ( # type: ignore[attr-defined]
WindowsProactorEventLoopPolicy,
WindowsSelectorEventLoopPolicy,
)
except ImportError:
pass
# Not affected
else:
if type(asyncio.get_event_loop_policy()) is WindowsProactorEventLoopPolicy:
# WindowsProactorEventLoopPolicy is not compatible with
# Tornado 6 fallback to the pre-3.8 default of Selector
asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy())
def _fix_sys_argv(main_script_path: str, args: list[str]) -> None:
"""sys.argv needs to exclude streamlit arguments and parameters
and be set to what a user's script may expect.
"""
import sys
sys.argv = [main_script_path, *list(args)]
def _on_server_start(server: Server) -> None:
_maybe_print_static_folder_warning(server.main_script_path)
_print_url(server.is_running_hello)
report_watchdog_availability()
# Load secrets.toml if it exists. If the file doesn't exist, this
# function will return without raising an exception. We catch any parse
# errors and display them here.
try:
secrets.load_if_toml_exists()
except Exception:
_LOGGER.exception("Failed to load secrets.toml file")
def maybe_open_browser() -> None:
if config.get_option("server.headless"):
# Don't open browser when in headless mode.
return
if config.is_manually_set("browser.serverAddress"):
addr = config.get_option("browser.serverAddress")
elif config.is_manually_set("server.address"):
if server_address_is_unix_socket():
# Don't open browser when server address is an unix socket
return
addr = config.get_option("server.address")
else:
addr = "localhost"
cli_util.open_browser(server_util.get_url(addr))
# Schedule the browser to open on the main thread.
asyncio.get_running_loop().call_soon(maybe_open_browser)
def _fix_pydeck_mapbox_api_warning() -> None:
"""Sets MAPBOX_API_KEY environment variable needed for PyDeck otherwise it
will throw an exception.
"""
if "MAPBOX_API_KEY" not in os.environ:
os.environ["MAPBOX_API_KEY"] = config.get_option("mapbox.token")
def _maybe_print_static_folder_warning(main_script_path: str) -> None:
"""Prints a warning if the static folder is misconfigured."""
if config.get_option("server.enableStaticServing"):
static_folder_path = file_util.get_app_static_dir(main_script_path)
if not os.path.isdir(static_folder_path):
cli_util.print_to_cli(
f"WARNING: Static file serving is enabled, but no static folder found "
f"at {static_folder_path}. To disable static file serving, "
f"set server.enableStaticServing to false.",
fg="yellow",
)
else:
# Raise warning when static folder size is larger than 1 GB
static_folder_size = file_util.get_directory_size(static_folder_path)
if static_folder_size > MAX_APP_STATIC_FOLDER_SIZE:
config.set_option("server.enableStaticServing", False)
cli_util.print_to_cli(
"WARNING: Static folder size is larger than 1GB. "
"Static file serving has been disabled.",
fg="yellow",
)
def _print_url(is_running_hello: bool) -> None:
if is_running_hello:
title_message = "Welcome to Streamlit. Check out our demo in your browser."
else:
title_message = "You can now view your Streamlit app in your browser."
named_urls = []
if config.is_manually_set("browser.serverAddress"):
named_urls = [
("URL", server_util.get_url(config.get_option("browser.serverAddress")))
]
elif (
config.is_manually_set("server.address") and not server_address_is_unix_socket()
):
named_urls = [
("URL", server_util.get_url(config.get_option("server.address"))),
]
elif server_address_is_unix_socket():
named_urls = [
("Unix Socket", config.get_option("server.address")),
]
else:
named_urls = [
("Local URL", server_util.get_url("localhost")),
]
internal_ip = net_util.get_internal_ip()
if internal_ip:
named_urls.append(("Network URL", server_util.get_url(internal_ip)))
if config.get_option("server.headless"):
external_ip = net_util.get_external_ip()
if external_ip:
named_urls.append(("External URL", server_util.get_url(external_ip)))
cli_util.print_to_cli("")
cli_util.print_to_cli(f" {title_message}", fg="blue", bold=True)
cli_util.print_to_cli("")
for url_name, url in named_urls:
cli_util.print_to_cli(f" {url_name}: ", nl=False, fg="blue")
cli_util.print_to_cli(url, bold=True)
cli_util.print_to_cli("")
if is_running_hello:
cli_util.print_to_cli(" Ready to create your own Python apps super quickly?")
cli_util.print_to_cli(" Head over to ", nl=False)
cli_util.print_to_cli("https://docs.streamlit.io", bold=True)
cli_util.print_to_cli("")
cli_util.print_to_cli(" May you create awesome apps!")
cli_util.print_to_cli("")
cli_util.print_to_cli("")
def load_config_options(flag_options: dict[str, Any]) -> None:
"""Load config options from config.toml files, then overlay the ones set by
flag_options.
The "streamlit run" command supports passing Streamlit's config options
as flags. This function reads through the config options set via flag,
massages them, and passes them to get_config_options() so that they
overwrite config option defaults and those loaded from config.toml files.
Parameters
----------
flag_options : dict[str, Any]
A dict of config options where the keys are the CLI flag version of the
config option names.
"""
# We want to filter out two things: values that are None, and values that
# are empty tuples. The latter is a special case that indicates that the
# no values were provided, and the config should reset to the default
options_from_flags = {
name.replace("_", "."): val
for name, val in flag_options.items()
if val is not None and val != ()
}
# Force a reparse of config files (if they exist). The result is cached
# for future calls.
config.get_config_options(force_reparse=True, options_from_flags=options_from_flags)
def _install_config_watchers(flag_options: dict[str, Any]) -> None:
def on_config_changed(_path: str) -> None:
load_config_options(flag_options)
for filename in config.get_config_files("config.toml"):
if os.path.exists(filename):
watch_file(filename, on_config_changed)
def run(
main_script_path: str,
is_hello: bool,
args: list[str],
flag_options: dict[str, Any],
*,
stop_immediately_for_testing: bool = False,
) -> None:
"""Run a script in a separate thread and start a server for the app.
This starts a blocking asyncio eventloop.
"""
_fix_sys_path(main_script_path)
_fix_tornado_crash()
_fix_sys_argv(main_script_path, args)
_fix_pydeck_mapbox_api_warning()
_install_config_watchers(flag_options)
# Create the server. It won't start running yet.
server = Server(main_script_path, is_hello)
async def run_server() -> None:
# Start the server
await server.start()
_on_server_start(server)
# Install a signal handler that will shut down the server
# and close all our threads
_set_up_signal_handler(server)
# return immediately if we're testing the server start
if stop_immediately_for_testing:
_LOGGER.debug("Stopping server immediately for testing")
server.stop()
# Wait until `Server.stop` is called, either by our signal handler, or
# by a debug websocket session.
await server.stopped
# Define a main function to handle the event loop logic
async def main() -> None:
await run_server()
# Handle running in existing event loop vs creating new one
running_in_event_loop = False
try:
# Check if we're already in an event loop
asyncio.get_running_loop()
running_in_event_loop = True
except RuntimeError:
# No running event loop - this is expected for normal CLI usage
pass
if running_in_event_loop:
_LOGGER.debug("Running server in existing event loop.")
# We're in an existing event loop.
task = asyncio.create_task(main(), name="bootstrap.run_server")
# Store task reference on the server to keep it alive
# This prevents the task from being garbage collected
server._bootstrap_task = task
else:
_maybe_install_uvloop(running_in_event_loop)
# No running event loop, so we can use asyncio.run
# This is the normal case when running streamlit from the command line
_LOGGER.debug("Starting new event loop for server")
asyncio.run(main())
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/web/cli.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
"""A script which is run when the Streamlit package is executed."""
from __future__ import annotations
import os
import sys
from collections.abc import Callable
from pathlib import Path
from typing import TYPE_CHECKING, Any, Final, TypeVar
# We cannot lazy-load click here because its used via decorators.
import click
from streamlit import config as _config
from streamlit.runtime import caching
from streamlit.runtime.credentials import Credentials, check_credentials
from streamlit.web import bootstrap
from streamlit.web.cache_storage_manager_config import (
create_default_cache_storage_manager,
)
if TYPE_CHECKING:
from streamlit.config_option import ConfigOption
ACCEPTED_FILE_EXTENSIONS: Final = ("py", "py3")
LOG_LEVELS: Final = ("error", "warning", "info", "debug")
def _convert_config_option_to_click_option(
config_option: ConfigOption,
) -> dict[str, Any]:
"""Composes given config option options as options for click lib."""
option = f"--{config_option.key}"
param = config_option.key.replace(".", "_")
description = config_option.description
if config_option.deprecated:
if description is None:
description = ""
description += (
f"\n {config_option.deprecation_text} - {config_option.expiration_date}"
)
return {
"param": param,
"description": description,
"type": config_option.type,
"option": option,
"envvar": config_option.env_var,
"multiple": config_option.multiple,
}
def _make_sensitive_option_callback(
config_option: ConfigOption,
) -> Callable[[click.Context, click.Parameter, Any], None]:
def callback(_ctx: click.Context, _param: click.Parameter, cli_value: Any) -> None:
if cli_value is None:
return
raise SystemExit(
f"Setting {config_option.key!r} option using the CLI flag is not allowed. "
f"Set this option in the configuration file or environment "
f"variable: {config_option.env_var!r}"
)
return callback
F = TypeVar("F", bound=Callable[..., Any])
def configurator_options(func: F) -> F:
"""Decorator that adds config param keys to click dynamically."""
for _, value in reversed(_config._config_options_template.items()):
parsed_parameter = _convert_config_option_to_click_option(value)
if value.sensitive:
# Display a warning if the user tries to set sensitive
# options using the CLI and exit with non-zero code.
click_option_kwargs = {
"expose_value": False,
"hidden": True,
"is_eager": True,
"callback": _make_sensitive_option_callback(value),
}
else:
click_option_kwargs = {
"show_envvar": True,
"envvar": parsed_parameter["envvar"],
}
config_option = click.option(
parsed_parameter["option"],
parsed_parameter["param"],
help=parsed_parameter["description"],
type=parsed_parameter["type"],
multiple=parsed_parameter["multiple"],
**click_option_kwargs, # type: ignore
)
func = config_option(func)
return func
def _download_remote(main_script_path: str, url_path: str) -> None:
"""Fetch remote file at url_path to main_script_path."""
import requests
from requests.exceptions import RequestException
with open(main_script_path, "wb") as fp:
try:
resp = requests.get(url_path, timeout=30)
resp.raise_for_status()
fp.write(resp.content)
except RequestException as e:
raise click.BadParameter(f"Unable to fetch {url_path}.\n{e}")
@click.group(context_settings={"auto_envvar_prefix": "STREAMLIT"})
@click.option("--log_level", show_default=True, type=click.Choice(LOG_LEVELS))
@click.version_option(prog_name="Streamlit")
def main(log_level: str = "info") -> None:
"""Try out a demo with:
$ streamlit hello
Or use the line below to run your own script:
$ streamlit run your_script.py
""" # noqa: D400
if log_level:
from streamlit.logger import get_logger
logger: Final = get_logger(__name__)
logger.warning(
"Setting the log level using the --log_level flag is unsupported."
"\nUse the --logger.level flag (after your streamlit command) instead."
)
@main.command("help")
def help() -> None: # noqa: A001
"""Print this help message."""
# We use _get_command_line_as_string to run some error checks but don't do
# anything with its return value.
_get_command_line_as_string()
# Pretend user typed 'streamlit --help' instead of 'streamlit help'.
sys.argv[1] = "--help"
main(prog_name="streamlit")
@main.command("version")
def main_version() -> None:
"""Print Streamlit's version number."""
# Pretend user typed 'streamlit --version' instead of 'streamlit version'
import sys
# We use _get_command_line_as_string to run some error checks but don't do
# anything with its return value.
_get_command_line_as_string()
sys.argv[1] = "--version"
main()
@main.command("docs")
def main_docs() -> None:
"""Show help in browser."""
click.echo("Showing help page in browser...")
from streamlit import cli_util
cli_util.open_browser("https://docs.streamlit.io")
@main.command("hello")
@configurator_options
def main_hello(**kwargs: Any) -> None:
"""Runs the Hello World script."""
from streamlit.hello import streamlit_app
filename = streamlit_app.__file__
_main_run(filename, flag_options=kwargs)
@main.command("run")
@configurator_options
@click.argument("target", default="streamlit_app.py", envvar="STREAMLIT_RUN_TARGET")
@click.argument("args", nargs=-1)
def main_run(target: str, args: list[str] | None = None, **kwargs: Any) -> None:
"""Run a Python script, piping stderr to Streamlit.
If omitted, the target script will be assumed to be "streamlit_app.py".
Otherwise, the target script should be one of the following:
- The path to a local Python file.
- The path to a local folder where "streamlit_app.py" can be found.
- A URL pointing to a Python file. In this case Streamlit will download the
file to a temporary file and run it.
To pass command-line arguments to the script, add " -- " before them. For example:
$ streamlit run my_app.py -- --my_arg1=123 my_arg2
↑
Your CLI args start after this.
"""
from streamlit import url_util
if url_util.is_url(target):
from streamlit.temporary_directory import TemporaryDirectory
with TemporaryDirectory() as temp_dir:
from urllib.parse import urlparse
url_subpath = urlparse(target).path
_check_extension_or_raise(url_subpath)
main_script_path = os.path.join(
temp_dir, url_subpath.strip("/").rsplit("/", 1)[-1]
)
# if this is a GitHub/Gist blob url, convert to a raw URL first.
url = url_util.process_gitblob_url(target)
_download_remote(main_script_path, url)
_main_run(main_script_path, args, flag_options=kwargs)
else:
path = Path(target)
if path.is_dir():
path /= "streamlit_app.py"
path_str = str(path)
_check_extension_or_raise(path_str)
if not path.exists():
raise click.BadParameter(f"File does not exist: {path}")
_main_run(path_str, args, flag_options=kwargs)
def _check_extension_or_raise(path_str: str) -> None:
_, extension = os.path.splitext(path_str)
if extension[1:] not in ACCEPTED_FILE_EXTENSIONS:
if extension[1:] == "":
raise click.BadArgumentUsage(
"Streamlit requires raw Python (.py) files, but the provided file has no extension.\n"
"For more information, please see https://docs.streamlit.io"
)
raise click.BadArgumentUsage(
f"Streamlit requires raw Python (.py) files, not {extension}.\n"
"For more information, please see https://docs.streamlit.io"
)
def _get_command_line_as_string() -> str | None:
import subprocess
parent = click.get_current_context().parent
if parent is None:
return None
if "streamlit.cli" in parent.command_path:
raise RuntimeError(
"Running streamlit via `python -m streamlit.cli <command>` is"
" unsupported. Please use `python -m streamlit <command>` instead."
)
cmd_line_as_list = [parent.command_path]
cmd_line_as_list.extend(sys.argv[1:])
return subprocess.list2cmdline(cmd_line_as_list)
def _main_run(
file: str,
args: list[str] | None = None,
flag_options: dict[str, Any] | None = None,
) -> None:
# Set the main script path to use it for config & secret files
# While its a bit suboptimal, we need to store this into a module-level
# variable before we load the config options via `load_config_options`
_config._main_script_path = os.path.abspath(file)
bootstrap.load_config_options(flag_options=flag_options or {})
if args is None:
args = []
if flag_options is None:
flag_options = {}
is_hello = _get_command_line_as_string() == "streamlit hello"
check_credentials()
bootstrap.run(file, is_hello, args, flag_options)
# SUBCOMMAND cache
@main.group("cache")
def cache() -> None:
"""Manage the Streamlit cache."""
pass
@cache.command("clear")
def cache_clear() -> None:
"""Clear st.cache_data and st.cache_resource caches."""
# in this `streamlit cache clear` cli command we cannot use the
# `cache_storage_manager from runtime (since runtime is not initialized)
# so we create a new cache_storage_manager instance that used in runtime,
# and call clear_all() method for it.
# This will not remove the in-memory cache.
cache_storage_manager = create_default_cache_storage_manager()
cache_storage_manager.clear_all()
caching.cache_resource.clear()
# SUBCOMMAND config
@main.group("config")
def config() -> None:
"""Manage Streamlit's config settings."""
pass
@config.command("show")
@configurator_options
def config_show(**kwargs: Any) -> None:
"""Show all of Streamlit's config settings."""
bootstrap.load_config_options(flag_options=kwargs)
_config.show_config()
# SUBCOMMAND activate
@main.group("activate", invoke_without_command=True)
@click.pass_context
def activate(ctx: click.Context) -> None:
"""Activate Streamlit by entering your email."""
if not ctx.invoked_subcommand:
Credentials.get_current().activate()
@activate.command("reset")
def activate_reset() -> None:
"""Reset Activation Credentials."""
Credentials.get_current().reset()
# SUBCOMMAND test
@main.group("test", hidden=True)
def test() -> None:
"""Internal-only commands used for testing.
These commands are not included in the output of `streamlit help`.
"""
pass
@test.command("prog_name")
def test_prog_name() -> None:
"""Assert that the program name is set to `streamlit test`.
This is used by our cli-smoke-tests to verify that the program name is set
to `streamlit ...` whether the streamlit binary is invoked directly or via
`python -m streamlit ...`.
"""
# We use _get_command_line_as_string to run some error checks but don't do
# anything with its return value.
_get_command_line_as_string()
parent = click.get_current_context().parent
if parent is None:
raise AssertionError("parent is None")
if parent.command_path != "streamlit test":
raise AssertionError(
f"Parent command path is {parent.command_path} not streamlit test."
)
@main.command("init")
@click.argument("directory", required=False)
def main_init(directory: str | None = None) -> None:
"""Initialize a new Streamlit project.
If DIRECTORY is specified, create it and initialize the project there.
Otherwise use the current directory.
"""
from pathlib import Path
project_dir = Path(directory) if directory else Path.cwd()
try:
project_dir.mkdir(exist_ok=True, parents=True)
except OSError as e:
raise click.ClickException(f"Failed to create directory: {e}")
# Create requirements.txt
(project_dir / "requirements.txt").write_text("streamlit\n", encoding="utf-8")
# Create streamlit_app.py
(project_dir / "streamlit_app.py").write_text(
"""import streamlit as st
st.title("🎈 My new app")
st.write(
"Let's start building! For help and inspiration, head over to [docs.streamlit.io](https://docs.streamlit.io/)."
)
""",
encoding="utf-8",
)
rel_path_str = str(directory) if directory else "."
click.secho("✨ Created new Streamlit app in ", nl=False)
click.secho(f"{rel_path_str}", fg="blue")
click.echo("🚀 Run it with: ", nl=False)
click.secho(f"streamlit run {rel_path_str}/streamlit_app.py", fg="blue")
if click.confirm("❓ Run the app now?", default=True):
app_path = project_dir / "streamlit_app.py"
click.echo("\nStarting Streamlit...")
_main_run(str(app_path))
if __name__ == "__main__":
main()
|
0
|
hf_public_repos/streamlit/lib/streamlit/web
|
hf_public_repos/streamlit/lib/streamlit/web/server/component_request_handler.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from typing import TYPE_CHECKING, Final, cast
import tornado.web
import streamlit.web.server.routes
from streamlit.logger import get_logger
from streamlit.web.server.component_file_utils import (
build_safe_abspath,
guess_content_type,
)
if TYPE_CHECKING:
from streamlit.components.types.base_component_registry import BaseComponentRegistry
_LOGGER: Final = get_logger(__name__)
class ComponentRequestHandler(tornado.web.RequestHandler):
def initialize(self, registry: BaseComponentRegistry) -> None:
self._registry = registry
def get(self, path: str) -> None:
parts = path.split("/")
component_name = parts[0]
component_root = self._registry.get_component_path(component_name)
if component_root is None:
self.write("not found")
self.set_status(404)
return
# Build a safe absolute path within the component root
filename = "/".join(parts[1:])
abspath = build_safe_abspath(component_root, filename)
if abspath is None:
self.write("forbidden")
self.set_status(403)
return
try:
with open(abspath, "rb") as file:
contents = file.read()
except OSError:
sanitized_abspath = abspath.replace("\n", "").replace("\r", "")
_LOGGER.exception(
"ComponentRequestHandler: GET %s read error", sanitized_abspath
)
self.write("read error")
self.set_status(404)
return
self.write(contents)
self.set_header("Content-Type", self.get_content_type(abspath))
self.set_extra_headers(path)
def set_extra_headers(self, path: str) -> None:
"""Disable cache for HTML files.
Other assets like JS and CSS are suffixed with their hash, so they can
be cached indefinitely.
"""
is_index_url = len(path) == 0
if is_index_url or path.endswith(".html"):
self.set_header("Cache-Control", "no-cache")
else:
self.set_header("Cache-Control", "public")
def set_default_headers(self) -> None:
if streamlit.web.server.routes.allow_all_cross_origin_requests():
self.set_header("Access-Control-Allow-Origin", "*")
elif streamlit.web.server.routes.is_allowed_origin(
origin := self.request.headers.get("Origin")
):
self.set_header("Access-Control-Allow-Origin", cast("str", origin))
def options(self) -> None:
"""/OPTIONS handler for preflight CORS checks."""
self.set_status(204)
self.finish()
@staticmethod
def get_content_type(abspath: str) -> str:
"""Returns the ``Content-Type`` header to be used for this request.
From tornado.web.StaticFileHandler.
"""
return guess_content_type(abspath)
@staticmethod
def get_url(file_id: str) -> str:
"""Return the URL for a component file with the given ID."""
return f"components/{file_id}"
|
0
|
hf_public_repos/streamlit/lib/streamlit/web
|
hf_public_repos/streamlit/lib/streamlit/web/server/__init__.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from streamlit.web.server.component_request_handler import ComponentRequestHandler
from streamlit.web.server.routes import (
allow_all_cross_origin_requests,
is_allowed_origin,
)
from streamlit.web.server.server import Server, server_address_is_unix_socket
from streamlit.web.server.stats_request_handler import StatsRequestHandler
__all__ = [
"ComponentRequestHandler",
"Server",
"StatsRequestHandler",
"allow_all_cross_origin_requests",
"is_allowed_origin",
"server_address_is_unix_socket",
]
|
0
|
hf_public_repos/streamlit/lib/streamlit/web
|
hf_public_repos/streamlit/lib/streamlit/web/server/routes.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import os
import re
from typing import TYPE_CHECKING, Any, Final, cast
import tornado.web
from streamlit import config, file_util
from streamlit.web.server.server_util import (
allowlisted_origins,
emit_endpoint_deprecation_notice,
is_xsrf_enabled,
)
if TYPE_CHECKING:
from collections.abc import Awaitable, Callable, Sequence
# Files that match this pattern do not get cached.
NO_CACHE_PATTERN = re.compile(r"(?:\.html$|^manifest\.json$)")
# The max-age value to send with cached assets. Set to one year.
STATIC_ASSET_CACHE_MAX_AGE_SECONDS: Final = 365 * 24 * 60 * 60
def allow_all_cross_origin_requests() -> bool:
"""True if cross-origin requests from any origin are allowed.
We only allow ALL cross-origin requests when CORS protection has been
disabled with server.enableCORS=False or if using the Node server in dev
mode. When in dev mode, we have a dev and prod port, which count as two
origins.
"""
return not config.get_option("server.enableCORS") or config.get_option(
"global.developmentMode"
)
def is_allowed_origin(origin: Any) -> bool:
if not isinstance(origin, str):
return False
return origin in allowlisted_origins()
class StaticFileHandler(tornado.web.StaticFileHandler):
def initialize(
self,
path: str,
default_filename: str | None = None,
reserved_paths: Sequence[str] = (),
) -> None:
self._reserved_paths = reserved_paths
super().initialize(path, default_filename)
def set_extra_headers(self, path: str) -> None:
"""Disable cache for HTML files and manifest.json.
Other assets like JS and CSS are suffixed with their hash, so they can
be cached indefinitely.
"""
is_index_url = len(path) == 0
if is_index_url or NO_CACHE_PATTERN.search(path):
self.set_header("Cache-Control", "no-cache")
else:
# For all other static files suffixed with their hash, we set a long cache time.
self.set_header(
"Cache-Control",
f"public, immutable, max-age={STATIC_ASSET_CACHE_MAX_AGE_SECONDS}",
)
def validate_absolute_path(self, root: str, absolute_path: str) -> str | None:
try:
return super().validate_absolute_path(root, absolute_path)
except tornado.web.HTTPError as e:
# If the file is not found, and there are no reserved paths,
# we try to serve the default file and allow the frontend to handle the issue.
if e.status_code == 404:
url_path = self.path
# self.path is OS specific file path, we convert it to a URL path
# for checking it against reserved paths.
if os.path.sep != "/":
url_path = url_path.replace(os.path.sep, "/")
if any(url_path.endswith(x) for x in self._reserved_paths):
raise
self.path = self.parse_url_path(self.default_filename or "index.html")
absolute_path = self.get_absolute_path(self.root, self.path)
return super().validate_absolute_path(root, absolute_path)
raise
def write_error(self, status_code: int, **kwargs: Any) -> None:
if status_code == 404:
index_file = os.path.join(file_util.get_static_dir(), "index.html")
self.render(index_file)
else:
super().write_error(status_code, **kwargs)
class AddSlashHandler(tornado.web.RequestHandler):
@tornado.web.addslash
def get(self) -> None:
pass
class RemoveSlashHandler(tornado.web.RequestHandler):
@tornado.web.removeslash
def get(self) -> None:
pass
class _SpecialRequestHandler(tornado.web.RequestHandler):
"""Superclass for "special" endpoints, like /healthz."""
def set_default_headers(self) -> None:
self.set_header("Cache-Control", "no-cache")
if allow_all_cross_origin_requests():
self.set_header("Access-Control-Allow-Origin", "*")
elif is_allowed_origin(origin := self.request.headers.get("Origin")):
self.set_header("Access-Control-Allow-Origin", cast("str", origin))
def options(self) -> None:
"""/OPTIONS handler for preflight CORS checks.
When a browser is making a CORS request, it may sometimes first
send an OPTIONS request, to check whether the server understands the
CORS protocol. This is optional, and doesn't happen for every request
or in every browser. If an OPTIONS request does get sent, and is not
then handled by the server, the browser will fail the underlying
request.
The proper way to handle this is to send a 204 response ("no content")
with the CORS headers attached. (These headers are automatically added
to every outgoing response, including OPTIONS responses,
via set_default_headers().)
See https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
"""
self.set_status(204)
self.finish()
class HealthHandler(_SpecialRequestHandler):
def initialize(self, callback: Callable[[], Awaitable[tuple[bool, str]]]) -> None:
"""Initialize the handler.
Parameters
----------
callback : callable
A function that returns True if the server is healthy
"""
self._callback = callback
async def get(self) -> None:
await self.handle_request()
# Some monitoring services only support the HTTP HEAD method for requests to
# healthcheck endpoints, so we support HEAD as well to play nicely with them.
async def head(self) -> None:
await self.handle_request()
async def handle_request(self) -> None:
if self.request.uri and "_stcore/" not in self.request.uri:
new_path = (
"/_stcore/script-health-check"
if "script-health-check" in self.request.uri
else "/_stcore/health"
)
emit_endpoint_deprecation_notice(self, new_path=new_path)
ok, msg = await self._callback()
if ok:
self.write(msg)
self.set_status(200)
# Tornado will set the _streamlit_xsrf cookie automatically for the page on
# request for the document. However, if the server is reset and
# server.enableXsrfProtection is updated, the browser does not reload the document.
# Manually setting the cookie on /healthz since it is pinged when the
# browser is disconnected from the server.
if is_xsrf_enabled():
cookie_kwargs = self.settings.get("xsrf_cookie_kwargs", {})
self.set_cookie(
self.settings.get("xsrf_cookie_name", "_streamlit_xsrf"),
self.xsrf_token,
**cookie_kwargs,
)
else:
# 503 = SERVICE_UNAVAILABLE
self.set_status(503)
self.write(msg)
_DEFAULT_ALLOWED_MESSAGE_ORIGINS = [
# Community-cloud related domains.
# We can remove these in the future if community cloud
# provides those domains via the host-config endpoint.
"https://devel.streamlit.test",
"https://*.streamlit.apptest",
"https://*.streamlitapp.test",
"https://*.streamlitapp.com",
"https://share.streamlit.io",
"https://share-demo.streamlit.io",
"https://share-head.streamlit.io",
"https://share-staging.streamlit.io",
"https://*.demo.streamlit.run",
"https://*.head.streamlit.run",
"https://*.staging.streamlit.run",
"https://*.streamlit.run",
"https://*.demo.streamlit.app",
"https://*.head.streamlit.app",
"https://*.staging.streamlit.app",
"https://*.streamlit.app",
]
class HostConfigHandler(_SpecialRequestHandler):
def initialize(self) -> None:
# Make a copy of the allowedOrigins list, since we might modify it later:
self._allowed_origins = _DEFAULT_ALLOWED_MESSAGE_ORIGINS.copy()
if (
config.get_option("global.developmentMode")
and "http://localhost" not in self._allowed_origins
):
# Allow messages from localhost in dev mode for testing of host <-> guest communication
self._allowed_origins.append("http://localhost")
async def get(self) -> None:
self.write(
{
"allowedOrigins": self._allowed_origins,
"useExternalAuthToken": False,
# Default host configuration settings.
"enableCustomParentMessages": False,
"enforceDownloadInNewTab": False,
"metricsUrl": "",
"blockErrorDialogs": False,
# Determines whether the crossOrigin attribute is set on some elements, e.g. img, video, audio, and if
# so with which value. One of None, "anonymous", "use-credentials".
"resourceCrossOriginMode": None,
}
)
self.set_status(200)
|
0
|
hf_public_repos/streamlit/lib/streamlit/web
|
hf_public_repos/streamlit/lib/streamlit/web/server/media_file_handler.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from typing import Any, cast
from urllib.parse import quote
import tornado.web
from streamlit.logger import get_logger
from streamlit.runtime.media_file_storage import MediaFileKind, MediaFileStorageError
from streamlit.runtime.memory_media_file_storage import (
MemoryMediaFileStorage,
get_extension_for_mimetype,
)
from streamlit.web.server import allow_all_cross_origin_requests, is_allowed_origin
_LOGGER = get_logger(__name__)
class MediaFileHandler(tornado.web.StaticFileHandler):
_storage: MemoryMediaFileStorage
@classmethod
def initialize_storage(cls, storage: MemoryMediaFileStorage) -> None:
"""Set the MemoryMediaFileStorage object used by instances of this
handler. Must be called on server startup.
"""
# This is a class method, rather than an instance method, because
# `get_content()` is a class method and needs to access the storage
# instance.
cls._storage = storage
def set_default_headers(self) -> None:
if allow_all_cross_origin_requests():
self.set_header("Access-Control-Allow-Origin", "*")
elif is_allowed_origin(origin := self.request.headers.get("Origin")):
self.set_header("Access-Control-Allow-Origin", cast("str", origin))
def set_extra_headers(self, path: str) -> None:
"""Add Content-Disposition header for downloadable files.
Set header value to "attachment" indicating that file should be saved
locally instead of displaying inline in browser.
We also set filename to specify the filename for downloaded files.
Used for serving downloadable files, like files stored via the
`st.download_button` widget.
"""
media_file = self._storage.get_file(path)
if media_file and media_file.kind == MediaFileKind.DOWNLOADABLE:
filename = media_file.filename
if not filename:
filename = f"streamlit_download{get_extension_for_mimetype(media_file.mimetype)}"
try:
# Check that the value can be encoded in latin1. Latin1 is
# the default encoding for headers.
filename.encode("latin1")
file_expr = f'filename="{filename}"'
except UnicodeEncodeError:
# RFC5987 syntax.
# See: https://datatracker.ietf.org/doc/html/rfc5987
file_expr = f"filename*=utf-8''{quote(filename)}"
self.set_header("Content-Disposition", f"attachment; {file_expr}")
# Overriding StaticFileHandler to use the MediaFileManager
#
# From the Tornado docs:
# To replace all interaction with the filesystem (e.g. to serve
# static content from a database), override `get_content`,
# `get_content_size`, `get_modified_time`, `get_absolute_path`, and
# `validate_absolute_path`.
def validate_absolute_path(
self,
root: str, # noqa: ARG002
absolute_path: str,
) -> str:
try:
self._storage.get_file(absolute_path)
except MediaFileStorageError:
_LOGGER.exception("MediaFileHandler: Missing file %s", absolute_path)
raise tornado.web.HTTPError(404, "not found")
return absolute_path
def get_content_size(self) -> int:
abspath = self.absolute_path
if abspath is None:
return 0
media_file = self._storage.get_file(abspath)
return media_file.content_size
def get_modified_time(self) -> None:
# We do not track last modified time, but this can be improved to
# allow caching among files in the MediaFileManager
return None
@classmethod
def get_absolute_path(cls, root: str, path: str) -> str: # noqa: ARG003
# All files are stored in memory, so the absolute path is just the
# path itself. In the MediaFileHandler, it's just the filename
return path
@classmethod
def get_content(
cls, abspath: str, start: int | None = None, end: int | None = None
) -> Any:
_LOGGER.debug("MediaFileHandler: GET %s", abspath)
try:
# abspath is the hash as used `get_absolute_path`
media_file = cls._storage.get_file(abspath)
except Exception:
_LOGGER.exception("MediaFileHandler: Missing file %s", abspath)
return None
_LOGGER.debug(
"MediaFileHandler: Sending %s file %s", media_file.mimetype, abspath
)
# If there is no start and end, just return the full content
if start is None and end is None:
return media_file.content
if start is None:
start = 0
if end is None:
end = len(media_file.content)
# content is bytes that work just by slicing supplied by start and end
return media_file.content[start:end]
|
0
|
hf_public_repos/streamlit/lib/streamlit/web
|
hf_public_repos/streamlit/lib/streamlit/web/server/server_util.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
"""Server related utility functions."""
from __future__ import annotations
from typing import TYPE_CHECKING, Final, Literal, cast
from urllib.parse import urljoin
from streamlit import config, net_util, url_util
from streamlit.runtime.secrets import secrets_singleton
from streamlit.type_util import is_version_less_than
if TYPE_CHECKING:
from collections.abc import Callable
from tornado.web import RequestHandler
# The port used for internal development.
DEVELOPMENT_PORT: Final = 3000
AUTH_COOKIE_NAME: Final = "_streamlit_user"
def allowlisted_origins() -> set[str]:
return {origin.strip() for origin in config.get_option("server.corsAllowedOrigins")}
def is_tornado_version_less_than(v: str) -> bool:
"""Return True if the current Tornado version is less than the input version.
Parameters
----------
v : str
Version string, e.g. "0.25.0"
Returns
-------
bool
Raises
------
InvalidVersion
If the version strings are not valid.
"""
import tornado
return is_version_less_than(tornado.version, v)
def is_url_from_allowed_origins(url: str) -> bool:
"""Return True if URL is from allowed origins (for CORS purpose).
Allowed origins:
1. localhost
2. The internal and external IP addresses of the machine where this
function was called from.
If `server.enableCORS` is False, this allows all origins.
"""
if not config.get_option("server.enableCORS"):
# Allow everything when CORS is disabled.
return True
hostname = url_util.get_hostname(url)
allowlisted_domains = [
url_util.get_hostname(origin) for origin in allowlisted_origins()
]
allowed_domains: list[str | None | Callable[[], str | None]] = [
# Check localhost first.
"localhost",
"0.0.0.0", # noqa: S104
"127.0.0.1",
# Try to avoid making unnecessary HTTP requests by checking if the user
# manually specified a server address.
_get_server_address_if_manually_set,
# Then try the options that depend on HTTP requests or opening sockets.
net_util.get_internal_ip,
net_util.get_external_ip,
*allowlisted_domains,
]
for allowed_domain in allowed_domains:
allowed_domain_str = (
allowed_domain() if callable(allowed_domain) else allowed_domain
)
if allowed_domain_str is None:
continue
if hostname == allowed_domain_str:
return True
return False
def get_cookie_secret() -> str:
"""Get the cookie secret.
If the user has not set a cookie secret, we generate a random one.
"""
cookie_secret: str = config.get_option("server.cookieSecret")
if secrets_singleton.load_if_toml_exists():
auth_section = secrets_singleton.get("auth")
if auth_section:
cookie_secret = auth_section.get("cookie_secret", cookie_secret)
return cookie_secret
def is_xsrf_enabled() -> bool:
csrf_enabled = config.get_option("server.enableXsrfProtection")
if not csrf_enabled and secrets_singleton.load_if_toml_exists():
auth_section = secrets_singleton.get("auth", None)
csrf_enabled = csrf_enabled or auth_section is not None
return cast("bool", csrf_enabled)
def _get_server_address_if_manually_set() -> str | None:
if config.is_manually_set("browser.serverAddress"):
return url_util.get_hostname(config.get_option("browser.serverAddress"))
return None
def make_url_path_regex(
*path: str,
trailing_slash: Literal["optional", "required", "prohibited"] = "optional",
) -> str:
"""Get a regex of the form ^/foo/bar/baz/?$ for a path (foo, bar, baz)."""
filtered_paths = [x.strip("/") for x in path if x] # Filter out falsely components.
path_format = r"^/%s$"
if trailing_slash == "optional":
path_format = r"^/%s/?$"
elif trailing_slash == "required":
path_format = r"^/%s/$"
return path_format % "/".join(filtered_paths)
def get_url(host_ip: str) -> str:
"""Get the URL for any app served at the given host_ip.
Parameters
----------
host_ip : str
The IP address of the machine that is running the Streamlit Server.
Returns
-------
str
The URL.
"""
protocol = "https" if config.get_option("server.sslCertFile") else "http"
port = _get_browser_address_bar_port()
base_path = config.get_option("server.baseUrlPath").strip("/")
if base_path:
base_path = "/" + base_path
host_ip = host_ip.strip("/")
return f"{protocol}://{host_ip}:{port}{base_path}"
def _get_browser_address_bar_port() -> int:
"""Get the app URL that will be shown in the browser's address bar.
That is, this is the port where static assets will be served from. In dev,
this is different from the URL that will be used to connect to the
server-browser websocket.
"""
if config.get_option("global.developmentMode"):
return DEVELOPMENT_PORT
return int(config.get_option("browser.serverPort"))
def emit_endpoint_deprecation_notice(handler: RequestHandler, new_path: str) -> None:
"""Emits the warning about deprecation of HTTP endpoint in the HTTP header."""
handler.set_header("Deprecation", True)
new_url = urljoin(f"{handler.request.protocol}://{handler.request.host}", new_path)
handler.set_header("Link", f'<{new_url}>; rel="alternate"')
|
0
|
hf_public_repos/streamlit/lib/streamlit/web
|
hf_public_repos/streamlit/lib/streamlit/web/server/browser_websocket_handler.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import hmac
import json
from typing import TYPE_CHECKING, Any, Final
from urllib.parse import urlparse
import tornado.concurrent
import tornado.locks
import tornado.netutil
import tornado.web
import tornado.websocket
from tornado.escape import utf8
from tornado.websocket import WebSocketHandler
from streamlit import config
from streamlit.logger import get_logger
from streamlit.proto.BackMsg_pb2 import BackMsg
from streamlit.runtime import Runtime, SessionClient, SessionClientDisconnectedError
from streamlit.runtime.runtime_util import serialize_forward_msg
from streamlit.web.server.server_util import (
AUTH_COOKIE_NAME,
is_url_from_allowed_origins,
is_xsrf_enabled,
)
if TYPE_CHECKING:
from collections.abc import Awaitable
from streamlit.proto.ForwardMsg_pb2 import ForwardMsg
_LOGGER: Final = get_logger(__name__)
class BrowserWebSocketHandler(WebSocketHandler, SessionClient):
"""Handles a WebSocket connection from the browser."""
def initialize(self, runtime: Runtime) -> None:
self._runtime = runtime
self._session_id: str | None = None
# The XSRF cookie is normally set when xsrf_form_html is used, but in a
# pure-Javascript application that does not use any regular forms we just
# need to read the self.xsrf_token manually to set the cookie as a side
# effect. See https://www.tornadoweb.org/en/stable/guide/security.html#cross-site-request-forgery-protection
# for more details.
if is_xsrf_enabled():
_ = self.xsrf_token
def get_signed_cookie(
self,
name: str,
value: str | None = None,
max_age_days: float = 31,
min_version: int | None = None,
) -> bytes | None:
"""Get a signed cookie from the request. Added for compatibility with
Tornado < 6.3.0.
See release notes: https://www.tornadoweb.org/en/stable/releases/v6.3.0.html#deprecation-notices
"""
try:
return super().get_signed_cookie(name, value, max_age_days, min_version)
except AttributeError:
return super().get_secure_cookie(name, value, max_age_days, min_version)
def check_origin(self, origin: str) -> bool:
"""Set up CORS."""
return super().check_origin(origin) or is_url_from_allowed_origins(origin)
def _validate_xsrf_token(self, supplied_token: str) -> bool:
"""Inspired by tornado.web.RequestHandler.check_xsrf_cookie method,
to check the XSRF token passed in Websocket connection header.
"""
_, token, _ = self._decode_xsrf_token(supplied_token)
_, expected_token, _ = self._get_raw_xsrf_token()
decoded_token = utf8(token)
decoded_expected_token = utf8(expected_token)
if not decoded_token or not decoded_expected_token:
return False
return hmac.compare_digest(decoded_token, decoded_expected_token)
def _parse_user_cookie(self, raw_cookie_value: bytes) -> dict[str, Any]:
"""Process the user cookie and extract the user info after
validating the origin. Origin is validated for security reasons.
"""
cookie_value = json.loads(raw_cookie_value)
user_info = {}
cookie_value_origin = cookie_value.get("origin", None)
parsed_origin_from_header = urlparse(self.request.headers["Origin"])
expected_origin_value = (
parsed_origin_from_header.scheme + "://" + parsed_origin_from_header.netloc
)
if cookie_value_origin == expected_origin_value:
user_info["is_logged_in"] = cookie_value.get("is_logged_in", False)
del cookie_value["origin"]
del cookie_value["is_logged_in"]
user_info.update(cookie_value)
else:
_LOGGER.error(
"Origin mismatch, the origin of websocket request is not the "
"same origin of redirect_uri in secrets.toml",
)
return user_info
def write_forward_msg(self, msg: ForwardMsg) -> None:
"""Send a ForwardMsg to the browser."""
try:
self.write_message(serialize_forward_msg(msg), binary=True)
except tornado.websocket.WebSocketClosedError as e:
raise SessionClientDisconnectedError from e
def select_subprotocol(self, subprotocols: list[str]) -> str | None:
"""Return the first subprotocol in the given list.
This method is used by Tornado to select a protocol when the
Sec-WebSocket-Protocol header is set in an HTTP Upgrade request.
NOTE: We repurpose the Sec-WebSocket-Protocol header here in a slightly
unfortunate (but necessary) way. The browser WebSocket API doesn't allow us to
set arbitrary HTTP headers, and this header is the only one where we have the
ability to set it to arbitrary values, so we use it to pass tokens (in this
case, the previous session ID to allow us to reconnect to it) from client to
server as the *third* value in the list.
The reason why the auth token is set as the third value is that:
- when Sec-WebSocket-Protocol is set, many clients expect the server to
respond with a selected subprotocol to use. We don't want that reply to be
the session token, so we by convention have the client always set the first
protocol to "streamlit" and select that.
- the second protocol in the list is reserved in some deployment environments
for an auth token that we currently don't use
"""
if subprotocols:
return subprotocols[0]
return None
def open(self, *args: Any, **kwargs: Any) -> Awaitable[None] | None:
user_info: dict[str, str | bool | None] = {}
existing_session_id = None
try:
ws_protocols = [
p.strip()
for p in self.request.headers["Sec-Websocket-Protocol"].split(",")
]
raw_cookie_value = self.get_signed_cookie(AUTH_COOKIE_NAME)
if is_xsrf_enabled() and raw_cookie_value:
csrf_protocol_value = ws_protocols[1]
if self._validate_xsrf_token(csrf_protocol_value):
user_info.update(self._parse_user_cookie(raw_cookie_value))
if len(ws_protocols) >= 3:
# See the NOTE in the docstring of the `select_subprotocol` method above
# for a detailed explanation of why this is done.
existing_session_id = ws_protocols[2]
except KeyError:
# Just let existing_session_id=None if we run into any error while trying to
# extract it from the Sec-Websocket-Protocol header.
pass
# Map in any user-configured headers. Note that these override anything coming
# from the auth cookie.
mapping_config = config.get_option("server.trustedUserHeaders")
for header_name, user_info_key in mapping_config.items():
header_values = self.request.headers.get_list(header_name)
if header_values:
# If there's at least one value, use the first value.
# NOTE: Tornado doesn't document the order of these values, so it's
# possible this won't be the first value that was received by the
# server.
user_info[user_info_key] = header_values[0]
else:
# Default to explicit None.
user_info[user_info_key] = None
self._session_id = self._runtime.connect_session(
client=self,
user_info=user_info,
existing_session_id=existing_session_id,
)
return None
def on_close(self) -> None:
if not self._session_id:
return
self._runtime.disconnect_session(self._session_id)
self._session_id = None
def get_compression_options(self) -> dict[Any, Any] | None:
"""Enable WebSocket compression.
Returning an empty dict enables websocket compression. Returning
None disables it.
(See the docstring in the parent class.)
"""
if config.get_option("server.enableWebsocketCompression"):
return {}
return None
def on_message(self, payload: str | bytes) -> None:
if not self._session_id:
return
try:
if isinstance(payload, str):
# Sanity check. (The frontend should only be sending us bytes;
# Protobuf.ParseFromString does not accept str input.)
raise TypeError( # noqa: TRY301
"WebSocket received an unexpected `str` message. "
"(We expect `bytes` only.)"
)
msg = BackMsg()
msg.ParseFromString(payload)
_LOGGER.debug("Received the following back message:\n%s", msg)
except Exception as ex:
_LOGGER.exception("Error deserializing back message")
self._runtime.handle_backmsg_deserialization_exception(self._session_id, ex)
return
# "debug_disconnect_websocket" and "debug_shutdown_runtime" are special
# developmentMode-only messages used in e2e tests to test reconnect handling and
# disabling widgets.
if msg.WhichOneof("type") == "debug_disconnect_websocket":
if config.get_option("global.developmentMode") or config.get_option(
"global.e2eTest"
):
self.close()
else:
_LOGGER.warning(
"Client tried to disconnect websocket when not in development mode or e2e testing."
)
elif msg.WhichOneof("type") == "debug_shutdown_runtime":
if config.get_option("global.developmentMode") or config.get_option(
"global.e2eTest"
):
self._runtime.stop()
else:
_LOGGER.warning(
"Client tried to shut down runtime when not in development mode or e2e testing."
)
else:
# AppSession handles all other BackMsg types.
self._runtime.handle_backmsg(self._session_id, msg)
|
0
|
hf_public_repos/streamlit/lib/streamlit/web
|
hf_public_repos/streamlit/lib/streamlit/web/server/stats_request_handler.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from typing import TYPE_CHECKING, cast
import tornado.web
from streamlit.web.server import allow_all_cross_origin_requests, is_allowed_origin
from streamlit.web.server.server_util import emit_endpoint_deprecation_notice
if TYPE_CHECKING:
from streamlit.proto.openmetrics_data_model_pb2 import MetricSet as MetricSetProto
from streamlit.runtime.stats import CacheStat, StatsManager
class StatsRequestHandler(tornado.web.RequestHandler):
def initialize(self, stats_manager: StatsManager) -> None:
self._manager = stats_manager
def set_default_headers(self) -> None:
if allow_all_cross_origin_requests():
self.set_header("Access-Control-Allow-Origin", "*")
elif is_allowed_origin(origin := self.request.headers.get("Origin")):
self.set_header("Access-Control-Allow-Origin", cast("str", origin))
def options(self) -> None:
"""/OPTIONS handler for preflight CORS checks."""
self.set_status(204)
self.finish()
def get(self) -> None:
if self.request.uri and "_stcore/" not in self.request.uri:
emit_endpoint_deprecation_notice(self, new_path="/_stcore/metrics")
stats = self._manager.get_stats()
# If the request asked for protobuf output, we return a serialized
# protobuf. Else we return text.
if "application/x-protobuf" in self.request.headers.get_list("Accept"):
self.write(self._stats_to_proto(stats).SerializeToString())
self.set_header("Content-Type", "application/x-protobuf")
self.set_status(200)
else:
self.write(self._stats_to_text(self._manager.get_stats()))
self.set_header("Content-Type", "application/openmetrics-text")
self.set_status(200)
@staticmethod
def _stats_to_text(stats: list[CacheStat]) -> str:
metric_type = "# TYPE cache_memory_bytes gauge"
metric_unit = "# UNIT cache_memory_bytes bytes"
metric_help = "# HELP Total memory consumed by a cache."
openmetrics_eof = "# EOF\n"
# Format: header, stats, EOF
result = [metric_type, metric_unit, metric_help]
result.extend(stat.to_metric_str() for stat in stats)
result.append(openmetrics_eof)
return "\n".join(result)
@staticmethod
def _stats_to_proto(stats: list[CacheStat]) -> MetricSetProto:
# Lazy load the import of this proto message for better performance:
from streamlit.proto.openmetrics_data_model_pb2 import GAUGE
from streamlit.proto.openmetrics_data_model_pb2 import (
MetricSet as MetricSetProto,
)
metric_set = MetricSetProto()
metric_family = metric_set.metric_families.add()
metric_family.name = "cache_memory_bytes"
metric_family.type = GAUGE
metric_family.unit = "bytes"
metric_family.help = "Total memory consumed by a cache."
for stat in stats:
metric_proto = metric_family.metrics.add()
stat.marshall_metric_proto(metric_proto)
metric_set = MetricSetProto()
metric_set.metric_families.append(metric_family)
return metric_set
|
0
|
hf_public_repos/streamlit/lib/streamlit/web
|
hf_public_repos/streamlit/lib/streamlit/web/server/oauth_authlib_routes.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import json
from typing import Any, Final, cast
from urllib.parse import urlparse
import tornado.web
from streamlit.auth_util import (
AuthCache,
decode_provider_token,
generate_default_provider_section,
get_secrets_auth_section,
)
from streamlit.errors import StreamlitAuthError
from streamlit.logger import get_logger
from streamlit.url_util import make_url_path
from streamlit.web.server.oidc_mixin import TornadoOAuth, TornadoOAuth2App
from streamlit.web.server.server_util import AUTH_COOKIE_NAME
_LOGGER: Final = get_logger(__name__)
auth_cache = AuthCache()
def create_oauth_client(provider: str) -> tuple[TornadoOAuth2App, str]:
"""Create an OAuth client for the given provider based on secrets.toml configuration."""
auth_section = get_secrets_auth_section()
if auth_section:
redirect_uri = auth_section.get("redirect_uri", None)
config = auth_section.to_dict()
else:
config = {}
redirect_uri = "/"
provider_section = config.setdefault(provider, {})
if not provider_section and provider == "default":
provider_section = generate_default_provider_section(auth_section)
config["default"] = provider_section
provider_client_kwargs = provider_section.setdefault("client_kwargs", {})
if "scope" not in provider_client_kwargs:
provider_client_kwargs["scope"] = "openid email profile"
if "prompt" not in provider_client_kwargs:
provider_client_kwargs["prompt"] = "select_account"
oauth = TornadoOAuth(config, cache=auth_cache)
oauth.register(provider)
return oauth.create_client(provider), redirect_uri # type: ignore[no-untyped-call]
class AuthHandlerMixin(tornado.web.RequestHandler):
"""Mixin for handling auth cookies. Added for compatibility with Tornado < 6.3.0."""
def initialize(self, base_url: str) -> None:
self.base_url = base_url
def redirect_to_base(self) -> None:
self.redirect(make_url_path(self.base_url, "/"))
def set_auth_cookie(self, user_info: dict[str, Any]) -> None:
serialized_cookie_value = json.dumps(user_info)
# log error if cookie value is larger than 4096 bytes
if len(serialized_cookie_value.encode()) > 4096:
_LOGGER.error(
"Authentication cookie size exceeds maximum browser limit of 4096 bytes. Authentication may fail."
)
try:
# We don't specify Tornado secure flag here because it leads to missing cookie on Safari.
# The OIDC flow should work only on secure context anyway (localhost or HTTPS),
# so specifying the secure flag here will not add anything in terms of security.
self.set_signed_cookie(
AUTH_COOKIE_NAME,
serialized_cookie_value,
httpOnly=True,
)
except AttributeError:
self.set_secure_cookie(
AUTH_COOKIE_NAME,
serialized_cookie_value,
httponly=True,
)
def clear_auth_cookie(self) -> None:
self.clear_cookie(AUTH_COOKIE_NAME)
class AuthLoginHandler(AuthHandlerMixin, tornado.web.RequestHandler):
async def get(self) -> None:
"""Redirect to the OAuth provider login page."""
provider = self._parse_provider_token()
if provider is None:
self.redirect_to_base()
return
client, redirect_uri = create_oauth_client(provider)
try:
client.authorize_redirect(self, redirect_uri)
except Exception as e:
self.send_error(400, reason=str(e))
def _parse_provider_token(self) -> str | None:
provider_token = self.get_argument("provider", None)
if provider_token is None:
return None
try:
payload = decode_provider_token(provider_token)
except StreamlitAuthError:
return None
return payload["provider"]
class AuthLogoutHandler(AuthHandlerMixin, tornado.web.RequestHandler):
def get(self) -> None:
self.clear_auth_cookie()
self.redirect_to_base()
class AuthCallbackHandler(AuthHandlerMixin, tornado.web.RequestHandler):
async def get(self) -> None:
provider = self._get_provider_by_state()
origin = self._get_origin_from_secrets()
if origin is None:
_LOGGER.error(
"Error, misconfigured origin for `redirect_uri` in secrets. ",
)
self.redirect_to_base()
return
error = self.get_argument("error", None)
if error:
error_description = self.get_argument("error_description", None)
sanitized_error = error.replace("\n", "").replace("\r", "")
sanitized_error_description = (
error_description.replace("\n", "").replace("\r", "")
if error_description
else None
)
_LOGGER.error(
"Error during authentication: %s. Error description: %s",
sanitized_error,
sanitized_error_description,
)
self.redirect_to_base()
return
if provider is None:
# See https://github.com/streamlit/streamlit/issues/13101
_LOGGER.warning(
"Missing provider for OAuth callback; this often indicates a stale "
"or replayed callback (for example, from browser back/forward "
"navigation).",
)
self.redirect_to_base()
return
client, _ = create_oauth_client(provider)
token = client.authorize_access_token(self)
user = cast("dict[str, Any]", token.get("userinfo"))
cookie_value = dict(user, origin=origin, is_logged_in=True)
if user:
self.set_auth_cookie(cookie_value)
else:
_LOGGER.error(
"Error, missing user info.",
)
self.redirect_to_base()
def _get_provider_by_state(self) -> str | None:
state_code_from_url = self.get_argument("state")
current_cache_keys = list(auth_cache.get_dict().keys())
state_provider_mapping = {}
for key in current_cache_keys:
_, _, recorded_provider, code = key.split("_")
state_provider_mapping[code] = recorded_provider
provider: str | None = state_provider_mapping.get(state_code_from_url)
return provider
def _get_origin_from_secrets(self) -> str | None:
redirect_uri = None
auth_section = get_secrets_auth_section()
if auth_section:
redirect_uri = auth_section.get("redirect_uri", None)
if not redirect_uri:
return None
redirect_uri_parsed = urlparse(redirect_uri)
origin_from_redirect_uri: str = (
redirect_uri_parsed.scheme + "://" + redirect_uri_parsed.netloc
)
return origin_from_redirect_uri
|
0
|
hf_public_repos/streamlit/lib/streamlit/web
|
hf_public_repos/streamlit/lib/streamlit/web/server/component_file_utils.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
"""Utilities for safely resolving component asset paths and content types.
These helpers are used by server handlers to construct safe absolute paths for
component files and to determine the appropriate ``Content-Type`` header for
responses. Path resolution prevents directory traversal by normalizing and
checking real paths against a component's root directory.
"""
from __future__ import annotations
import mimetypes
import os
from typing import Final
_OCTET_STREAM: Final[str] = "application/octet-stream"
def build_safe_abspath(component_root: str, relative_url_path: str) -> str | None:
"""Build an absolute path inside ``component_root`` if safe.
The function joins ``relative_url_path`` with ``component_root`` and
normalizes and resolves symlinks. If the resulting path escapes the
component root, ``None`` is returned to indicate a forbidden traversal.
Parameters
----------
component_root : str
Absolute path to the component's root directory.
relative_url_path : str
Relative URL path from the component root to the requested file.
Returns
-------
str or None
The resolved absolute path if it stays within ``component_root``;
otherwise ``None`` when the path would traverse outside the root.
"""
root_real = os.path.realpath(component_root)
candidate = os.path.normpath(os.path.join(root_real, relative_url_path))
candidate_real = os.path.realpath(candidate)
try:
# Ensure the candidate stays within the real component root
if os.path.commonpath([root_real, candidate_real]) != root_real:
return None
except ValueError:
# On some platforms, commonpath can raise if drives differ; treat as forbidden.
return None
return candidate_real
def guess_content_type(abspath: str) -> str:
"""Guess the HTTP ``Content-Type`` for a file path.
This logic mirrors Tornado's ``StaticFileHandler`` by respecting encoding
metadata from ``mimetypes.guess_type`` and falling back to
``application/octet-stream`` when no specific type can be determined.
Parameters
----------
abspath : str
Absolute file path used for type detection (only the suffix matters).
Returns
-------
str
Guessed content type string suitable for the ``Content-Type`` header.
"""
mime_type, encoding = mimetypes.guess_type(abspath)
# per RFC 6713, use the appropriate type for a gzip compressed file
if encoding == "gzip":
return "application/gzip"
# As of 2015-07-21 there is no bzip2 encoding defined at
# http://www.iana.org/assignments/media-types/media-types.xhtml
# So for that (and any other encoding), use octet-stream.
if encoding is not None:
return _OCTET_STREAM
if mime_type is not None:
return mime_type
# if mime_type not detected, use application/octet-stream
return _OCTET_STREAM
|
0
|
hf_public_repos/streamlit/lib/streamlit/web
|
hf_public_repos/streamlit/lib/streamlit/web/server/authlib_tornado_integration.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from authlib.integrations.base_client import (
FrameworkIntegration,
)
from streamlit.runtime.secrets import AttrDict
if TYPE_CHECKING:
from collections.abc import Sequence
from streamlit.web.server.oidc_mixin import TornadoOAuth
class TornadoIntegration(FrameworkIntegration):
def update_token(
self,
token: dict[str, Any],
refresh_token: dict[str, Any] | None = None,
access_token: dict[str, Any] | None = None,
) -> None:
"""We do not support access token refresh, since we obtain and operate only on
identity tokens. We override this method explicitly to implement all abstract
methods of base class.
"""
@staticmethod
def load_config( # type: ignore[override]
oauth: TornadoOAuth, name: str, params: Sequence[str]
) -> dict[str, Any]:
"""Configure Authlib integration with provider parameters
specified in secrets.toml.
"""
# oauth.config here is an auth section from secrets.toml
# We parse it here to transform nested AttrDict (for client_kwargs value)
# to dict so Authlib can work with it under the hood.
if not oauth.config:
return {}
prepared_config = {}
for key in params:
value = oauth.config.get(name, {}).get(key, None)
if isinstance(value, AttrDict):
# We want to modify client_kwargs further after loading server metadata
value = value.to_dict()
if value is not None:
prepared_config[key] = value
return prepared_config
|
0
|
hf_public_repos/streamlit/lib/streamlit/web
|
hf_public_repos/streamlit/lib/streamlit/web/server/oidc_mixin.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
# mypy: disable-error-code="no-untyped-call"
from __future__ import annotations
from typing import TYPE_CHECKING, Any, cast
from authlib.integrations.base_client import (
BaseApp,
BaseOAuth,
OAuth2Mixin,
OAuthError,
OpenIDMixin,
)
from authlib.integrations.requests_client import (
OAuth2Session,
)
from streamlit.web.server.authlib_tornado_integration import TornadoIntegration
if TYPE_CHECKING:
from collections.abc import Callable
import tornado.web
from streamlit.auth_util import AuthCache
class TornadoOAuth2App(OAuth2Mixin, OpenIDMixin, BaseApp):
client_cls = OAuth2Session
def load_server_metadata(self) -> dict[str, Any]:
"""We enforce S256 code challenge method if it is supported by the server."""
result = cast("dict[str, Any]", super().load_server_metadata())
if "S256" in result.get("code_challenge_methods_supported", []):
self.client_kwargs["code_challenge_method"] = "S256"
return result
def authorize_redirect(
self,
request_handler: tornado.web.RequestHandler,
redirect_uri: Any = None,
**kwargs: Any,
) -> None:
"""Create a HTTP Redirect for Authorization Endpoint.
:param request_handler: HTTP request instance from Tornado.
:param redirect_uri: Callback or redirect URI for authorization.
:param kwargs: Extra parameters to include.
:return: A HTTP redirect response.
"""
auth_context = self.create_authorization_url(redirect_uri, **kwargs)
self._save_authorize_data(redirect_uri=redirect_uri, **auth_context)
request_handler.redirect(auth_context["url"], status=302)
def authorize_access_token(
self, request_handler: tornado.web.RequestHandler, **kwargs: Any
) -> dict[str, Any]:
"""
:param request_handler: HTTP request instance from Tornado.
:return: A token dict.
"""
error = request_handler.get_argument("error", None)
if error:
description = request_handler.get_argument("error_description", None)
raise OAuthError(error=error, description=description)
params = {
"code": request_handler.get_argument("code"),
"state": request_handler.get_argument("state"),
}
session = None
claims_options = kwargs.pop("claims_options", None)
state_data = self.framework.get_state_data(session, params.get("state"))
self.framework.clear_state_data(session, params.get("state"))
params = self._format_state_params(state_data, params) # type: ignore[attr-defined]
token = self.fetch_access_token(**params, **kwargs)
if "id_token" in token and "nonce" in state_data:
userinfo = self.parse_id_token(
token, nonce=state_data["nonce"], claims_options=claims_options
)
token = {**token, "userinfo": userinfo}
return cast("dict[str, Any]", token)
def _save_authorize_data(self, **kwargs: Any) -> None:
"""Authlib underlying uses the concept of "session" to store state data.
In Tornado, we don't have a session, so we use the framework's cache option.
"""
state = kwargs.pop("state", None)
if state:
session = None
self.framework.set_state_data(session, state, kwargs)
else:
raise RuntimeError("Missing state value")
class TornadoOAuth(BaseOAuth):
oauth2_client_cls = TornadoOAuth2App
framework_integration_cls = TornadoIntegration
def __init__(
self,
config: dict[str, Any] | None = None,
cache: AuthCache | None = None,
fetch_token: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
update_token: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
):
super().__init__(
cache=cache, fetch_token=fetch_token, update_token=update_token
)
self.config = config
|
0
|
hf_public_repos/streamlit/lib/streamlit/web
|
hf_public_repos/streamlit/lib/streamlit/web/server/upload_file_request_handler.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from typing import TYPE_CHECKING, Any, cast
import tornado.httputil
import tornado.web
from streamlit import config
from streamlit.runtime.uploaded_file_manager import UploadedFileRec
from streamlit.web.server import routes, server_util
from streamlit.web.server.server_util import is_xsrf_enabled
if TYPE_CHECKING:
from collections.abc import Callable
from streamlit.runtime.memory_uploaded_file_manager import MemoryUploadedFileManager
class UploadFileRequestHandler(tornado.web.RequestHandler):
"""Implements the POST /upload_file endpoint."""
def initialize(
self,
file_mgr: MemoryUploadedFileManager,
is_active_session: Callable[[str], bool],
) -> None:
"""
Parameters
----------
file_mgr : UploadedFileManager
The server's singleton UploadedFileManager. All file uploads
go here.
is_active_session:
A function that returns true if a session_id belongs to an active
session.
"""
self._file_mgr = file_mgr
self._is_active_session = is_active_session
def set_default_headers(self) -> None:
self.set_header("Access-Control-Allow-Methods", "PUT, OPTIONS, DELETE")
self.set_header("Access-Control-Allow-Headers", "Content-Type")
if is_xsrf_enabled():
self.set_header(
"Access-Control-Allow-Origin",
server_util.get_url(config.get_option("browser.serverAddress")),
)
self.set_header("Access-Control-Allow-Headers", "X-Xsrftoken, Content-Type")
self.set_header("Vary", "Origin")
self.set_header("Access-Control-Allow-Credentials", "true")
elif routes.allow_all_cross_origin_requests():
self.set_header("Access-Control-Allow-Origin", "*")
elif routes.is_allowed_origin(origin := self.request.headers.get("Origin")):
self.set_header("Access-Control-Allow-Origin", cast("str", origin))
def options(self, **kwargs: Any) -> None:
"""/OPTIONS handler for preflight CORS checks.
When a browser is making a CORS request, it may sometimes first
send an OPTIONS request, to check whether the server understands the
CORS protocol. This is optional, and doesn't happen for every request
or in every browser. If an OPTIONS request does get sent, and is not
then handled by the server, the browser will fail the underlying
request.
The proper way to handle this is to send a 204 response ("no content")
with the CORS headers attached. (These headers are automatically added
to every outgoing response, including OPTIONS responses,
via set_default_headers().)
See https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
"""
self.set_status(204)
self.finish()
def put(self, **kwargs: Any) -> None:
"""Receive an uploaded file and add it to our UploadedFileManager."""
args: dict[str, list[bytes]] = {}
files: dict[str, list[Any]] = {}
if not self.path_kwargs:
# This is not expected to happen with normal Streamlit usage.
self.send_error(
400,
reason="No path arguments provided. Please provide a session_id and file_id in the URL.",
)
return
session_id = self.path_kwargs["session_id"]
file_id = self.path_kwargs["file_id"]
tornado.httputil.parse_body_arguments(
content_type=self.request.headers["Content-Type"],
body=self.request.body,
arguments=args,
files=files,
)
try:
if not self._is_active_session(session_id):
self.send_error(400, reason="Invalid session_id")
return
except Exception as ex:
self.send_error(400, reason=str(ex))
return
uploaded_files: list[UploadedFileRec] = []
for flist in files.values():
uploaded_files.extend(
UploadedFileRec(
file_id=file_id,
name=file["filename"],
type=file["content_type"],
data=file["body"],
)
for file in flist
)
if len(uploaded_files) != 1:
self.send_error(
400, reason=f"Expected 1 file, but got {len(uploaded_files)}"
)
return
self._file_mgr.add_file(session_id=session_id, file=uploaded_files[0])
self.set_status(204)
def delete(self, **kwargs: Any) -> None:
"""Delete file request handler."""
if not self.path_kwargs:
self.send_error(
400,
reason="No path arguments provided. Please provide a session_id and file_id in the URL.",
)
return
session_id = self.path_kwargs["session_id"]
file_id = self.path_kwargs["file_id"]
self._file_mgr.remove_file(session_id=session_id, file_id=file_id)
self.set_status(204)
|
0
|
hf_public_repos/streamlit/lib/streamlit/web
|
hf_public_repos/streamlit/lib/streamlit/web/server/app_static_file_handler.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import os
from pathlib import Path
from typing import Final
import tornado.web
from streamlit.logger import get_logger
_LOGGER: Final = get_logger(__name__)
# We agreed on these limitations for the initial release of static file sharing,
# based on security concerns from the SiS and Community Cloud teams
# The maximum possible size of single serving static file.
MAX_APP_STATIC_FILE_SIZE = 200 * 1024 * 1024 # 200 MB
# The list of file extensions that we serve with the corresponding Content-Type header.
# All files with other extensions will be served with Content-Type: text/plain
SAFE_APP_STATIC_FILE_EXTENSIONS = (
# Common image types:
".jpg",
".jpeg",
".png",
".gif",
".webp",
# Common font types:
".otf",
".ttf",
".woff",
".woff2",
# Other types:
".pdf",
".xml",
".json",
)
class AppStaticFileHandler(tornado.web.StaticFileHandler):
def initialize(self, path: str, default_filename: str | None = None) -> None:
super().initialize(path, default_filename)
def validate_absolute_path(self, root: str, absolute_path: str) -> str | None:
full_path = os.path.abspath(absolute_path)
ret_val = super().validate_absolute_path(root, absolute_path)
if os.path.isdir(full_path):
# we don't want to serve directories, and serve only files
raise tornado.web.HTTPError(404)
if os.path.commonpath([full_path, root]) != root:
# Don't allow misbehaving clients to break out of the static files directory
_LOGGER.warning(
"Serving files outside of the static directory is not supported"
)
raise tornado.web.HTTPError(404)
if (
os.path.exists(full_path)
and os.path.getsize(full_path) > MAX_APP_STATIC_FILE_SIZE
):
raise tornado.web.HTTPError(
404,
"File is too large, its size should not exceed "
f"{MAX_APP_STATIC_FILE_SIZE} bytes",
reason="File is too large",
)
return ret_val
def set_default_headers(self) -> None:
# CORS protection is disabled because we need access to this endpoint
# from the inner iframe.
self.set_header("Access-Control-Allow-Origin", "*")
def set_extra_headers(self, path: str) -> None:
if Path(path).suffix not in SAFE_APP_STATIC_FILE_EXTENSIONS:
self.set_header("Content-Type", "text/plain")
self.set_header("X-Content-Type-Options", "nosniff")
|
0
|
hf_public_repos/streamlit/lib/streamlit/web
|
hf_public_repos/streamlit/lib/streamlit/web/server/bidi_component_request_handler.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
"""Serve static assets for Custom Components v2.
This module defines a Tornado ``RequestHandler`` that serves static files for
Custom Components v2 from their registered component directories. Requests are
resolved safely within the component's root to avoid directory traversal and are
served with appropriate content type and cache headers. CORS headers are applied
based on the server configuration.
"""
from __future__ import annotations
import os
from typing import TYPE_CHECKING, Final, cast
import tornado.web
import streamlit.web.server.routes
from streamlit.logger import get_logger
from streamlit.web.server.component_file_utils import (
build_safe_abspath,
guess_content_type,
)
if TYPE_CHECKING:
from streamlit.components.v2.component_manager import BidiComponentManager
_LOGGER: Final = get_logger(__name__)
class BidiComponentRequestHandler(tornado.web.RequestHandler):
"""Request handler for serving Custom Components v2 static assets.
The handler resolves a requested path to a registered component's asset
within its component root, writes the file contents to the response, and
sets appropriate ``Content-Type`` and cache headers. If the component or
asset cannot be found, a suitable HTTP status is returned.
"""
def initialize(self, component_manager: BidiComponentManager) -> None:
"""Initialize the handler with the given component manager.
Parameters
----------
component_manager : BidiComponentManager
Manager used to look up registered components and their root paths.
"""
self._component_manager = component_manager
def get(self, path: str) -> None:
"""Serve a component asset for the given URL path.
The first path segment is interpreted as the component name. The rest
of the path is resolved to a file within that component's root
directory. If the file exists and is readable, its bytes are written to
the response and the ``Content-Type`` header is set based on the file
type.
Parameters
----------
path : str
Request path in the form ``"<component_name>/<relative_file>"``.
Notes
-----
This method writes directly to the response and sets appropriate HTTP
status codes on error (``404`` for missing components/files, ``403`` for
forbidden paths).
"""
parts = path.split("/")
component_name = parts[0]
component_def = self._component_manager.get(component_name)
if component_def is None:
self.write("not found")
self.set_status(404)
return
# Get the component path from the component manager
component_path = self._component_manager.get_component_path(component_name)
if component_path is None:
self.write("not found")
self.set_status(404)
return
# Build a safe absolute path within the component root
filename = "/".join(parts[1:])
# If no file segment is provided (e.g. only component name or trailing slash),
# treat as not found rather than attempting to open a directory.
if not filename or filename.endswith("/"):
self.write("not found")
self.set_status(404)
return
abspath = build_safe_abspath(component_path, filename)
if abspath is None:
self.write("forbidden")
self.set_status(403)
return
# If the resolved path is a directory, return 404 not found.
if os.path.isdir(abspath):
self.write("not found")
self.set_status(404)
return
try:
with open(abspath, "rb") as file:
contents = file.read()
except OSError:
sanitized_abspath = abspath.replace("\n", "").replace("\r", "")
_LOGGER.exception(
"BidiComponentRequestHandler: GET %s read error", sanitized_abspath
)
self.write("read error")
self.set_status(404)
return
self.write(contents)
self.set_header("Content-Type", guess_content_type(abspath))
self.set_extra_headers(path)
def set_extra_headers(self, path: str) -> None:
"""Disable cache for HTML files.
We assume other assets like JS and CSS are suffixed with their hash, so
they can be cached indefinitely.
"""
if path.endswith(".html"):
self.set_header("Cache-Control", "no-cache")
else:
self.set_header("Cache-Control", "public")
def set_default_headers(self) -> None:
"""Set default CORS headers based on server configuration.
If cross-origin requests are fully allowed, ``Access-Control-Allow-
Origin`` is set to ``"*"``. Otherwise, if the request ``Origin`` header
is an allowed origin, the header is echoed back.
"""
if streamlit.web.server.routes.allow_all_cross_origin_requests():
self.set_header("Access-Control-Allow-Origin", "*")
elif streamlit.web.server.routes.is_allowed_origin(
origin := self.request.headers.get("Origin")
):
self.set_header("Access-Control-Allow-Origin", cast("str", origin))
def options(self) -> None:
"""Handle preflight CORS requests.
Returns
-------
None
Responds with HTTP ``204 No Content`` to indicate that the actual
request can proceed.
"""
self.set_status(204)
self.finish()
@staticmethod
def get_url(file_id: str) -> str:
"""Return the URL for a component asset identified by ``file_id``.
Parameters
----------
file_id : str
Component file identifier (typically a relative path or hashed
filename).
Returns
-------
str
Relative URL path for the resource, to be joined with the server
base URL.
Examples
--------
>>> BidiComponentRequestHandler.get_url("my_component/main.js")
'_stcore/bidi-components/my_component/main.js'
"""
return f"_stcore/bidi-components/{file_id}"
|
0
|
hf_public_repos/streamlit/lib/streamlit/web
|
hf_public_repos/streamlit/lib/streamlit/web/server/server.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import errno
import logging
import mimetypes
import os
import sys
from pathlib import Path
from typing import TYPE_CHECKING, Any, Final
import tornado.web
from tornado.httpserver import HTTPServer
from streamlit import cli_util, config, file_util, util
from streamlit.auth_util import is_authlib_installed
from streamlit.config_option import ConfigOption
from streamlit.logger import get_logger
from streamlit.runtime import Runtime, RuntimeConfig, RuntimeState
from streamlit.runtime.memory_media_file_storage import MemoryMediaFileStorage
from streamlit.runtime.memory_session_storage import MemorySessionStorage
from streamlit.runtime.memory_uploaded_file_manager import MemoryUploadedFileManager
from streamlit.runtime.runtime_util import get_max_message_size_bytes
from streamlit.web.cache_storage_manager_config import (
create_default_cache_storage_manager,
)
from streamlit.web.server.app_static_file_handler import AppStaticFileHandler
from streamlit.web.server.bidi_component_request_handler import (
BidiComponentRequestHandler,
)
from streamlit.web.server.browser_websocket_handler import BrowserWebSocketHandler
from streamlit.web.server.component_request_handler import ComponentRequestHandler
from streamlit.web.server.media_file_handler import MediaFileHandler
from streamlit.web.server.routes import (
AddSlashHandler,
HealthHandler,
HostConfigHandler,
RemoveSlashHandler,
StaticFileHandler,
)
from streamlit.web.server.server_util import (
get_cookie_secret,
is_tornado_version_less_than,
is_xsrf_enabled,
make_url_path_regex,
)
from streamlit.web.server.stats_request_handler import StatsRequestHandler
from streamlit.web.server.upload_file_request_handler import UploadFileRequestHandler
if TYPE_CHECKING:
import asyncio
from collections.abc import Awaitable
from ssl import SSLContext
_LOGGER: Final = get_logger(__name__)
def _get_websocket_ping_interval_and_timeout() -> tuple[int, int]:
"""Get the websocket ping interval and timeout from config or defaults.
Returns
-------
tuple: (ping_interval, ping_timeout)
"""
configured_interval = config.get_option("server.websocketPingInterval")
if configured_interval is not None:
# User has explicitly set a value
interval = int(configured_interval)
# Warn if using Tornado 6.5+ with low interval
if not is_tornado_version_less_than("6.5.0") and interval < 30:
_LOGGER.warning(
"You have set server.websocketPingInterval to %s, but Tornado >= 6.5 "
"requires websocket_ping_interval >= websocket_ping_timeout. "
"To comply, we are setting both the ping interval and ping timeout to %s. "
"Depending on the specific deployment setup, this may cause connection issues.",
interval,
interval,
)
# When user configures interval, set timeout to match
return interval, interval
# Default behavior: respect Tornado version for interval, always 30s timeout
default_interval = 1 if is_tornado_version_less_than("6.5.0") else 30
return default_interval, 30
def get_tornado_settings() -> dict[str, Any]:
"""Get Tornado settings for the server.
This is a function to allow for testing and dynamic configuration.
"""
ping_interval, ping_timeout = _get_websocket_ping_interval_and_timeout()
return {
# Gzip HTTP responses.
"compress_response": True,
# Ping interval for websocket keepalive.
# With recent versions of Tornado, this value must be greater than or
# equal to websocket_ping_timeout.
# For details, see https://github.com/tornadoweb/tornado/pull/3376
# For compatibility with older versions of Tornado, we set the value to 1.
"websocket_ping_interval": ping_interval,
# If we don't get a ping response within this time, the connection
# is timed out.
"websocket_ping_timeout": ping_timeout,
"xsrf_cookie_name": "_streamlit_xsrf",
}
# When server.port is not available it will look for the next available port
# up to MAX_PORT_SEARCH_RETRIES.
MAX_PORT_SEARCH_RETRIES: Final = 100
# When server.address starts with this prefix, the server will bind
# to an unix socket.
UNIX_SOCKET_PREFIX: Final = "unix://"
# Please make sure to also update frontend/app/vite.config.ts
# dev server proxy when changing or updating these endpoints as well
# as the endpoints in frontend/connection/src/DefaultStreamlitEndpoints
MEDIA_ENDPOINT: Final = "/media"
COMPONENT_ENDPOINT: Final = "/component"
BIDI_COMPONENT_ENDPOINT: Final = "/_stcore/bidi-components"
STATIC_SERVING_ENDPOINT: Final = "/app/static"
UPLOAD_FILE_ENDPOINT: Final = "/_stcore/upload_file"
STREAM_ENDPOINT: Final = r"_stcore/stream"
METRIC_ENDPOINT: Final = r"(?:st-metrics|_stcore/metrics)"
MESSAGE_ENDPOINT: Final = r"_stcore/message"
NEW_HEALTH_ENDPOINT: Final = "_stcore/health"
HEALTH_ENDPOINT: Final = rf"(?:healthz|{NEW_HEALTH_ENDPOINT})"
HOST_CONFIG_ENDPOINT: Final = r"_stcore/host-config"
SCRIPT_HEALTH_CHECK_ENDPOINT: Final = (
r"(?:script-health-check|_stcore/script-health-check)"
)
OAUTH2_CALLBACK_ENDPOINT: Final = "/oauth2callback"
AUTH_LOGIN_ENDPOINT: Final = "/auth/login"
AUTH_LOGOUT_ENDPOINT: Final = "/auth/logout"
class RetriesExceededError(Exception):
pass
def server_port_is_manually_set() -> bool:
return config.is_manually_set("server.port")
def server_address_is_unix_socket() -> bool:
address = config.get_option("server.address")
return address is not None and address.startswith(UNIX_SOCKET_PREFIX)
def start_listening(app: tornado.web.Application) -> None:
"""Makes the server start listening at the configured port.
In case the port is already taken it tries listening to the next available
port. It will error after MAX_PORT_SEARCH_RETRIES attempts.
"""
cert_file = config.get_option("server.sslCertFile")
key_file = config.get_option("server.sslKeyFile")
ssl_options = _get_ssl_options(cert_file, key_file)
http_server = HTTPServer(
app,
max_buffer_size=config.get_option("server.maxUploadSize") * 1024 * 1024,
ssl_options=ssl_options,
)
if server_address_is_unix_socket():
start_listening_unix_socket(http_server)
else:
start_listening_tcp_socket(http_server)
def _get_ssl_options(cert_file: str | None, key_file: str | None) -> SSLContext | None:
if bool(cert_file) != bool(key_file):
_LOGGER.error(
"Options 'server.sslCertFile' and 'server.sslKeyFile' must "
"be set together. Set missing options or delete existing options."
)
sys.exit(1)
if cert_file and key_file:
# ssl_ctx.load_cert_chain raise exception as below, but it is not
# sufficiently user-friendly
# FileNotFoundError: [Errno 2] No such file or directory
if not Path(cert_file).exists():
_LOGGER.error("Cert file '%s' does not exist.", cert_file)
sys.exit(1)
if not Path(key_file).exists():
_LOGGER.error("Key file '%s' does not exist.", key_file)
sys.exit(1)
import ssl
ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
# When the SSL certificate fails to load, an exception is raised as below,
# but it is not sufficiently user-friendly.
# ssl.SSLError: [SSL] PEM lib (_ssl.c:4067)
try:
ssl_ctx.load_cert_chain(cert_file, key_file)
except ssl.SSLError:
_LOGGER.exception(
"Failed to load SSL certificate. Make sure "
"cert file '%s' and key file '%s' are correct.",
cert_file,
key_file,
)
sys.exit(1)
return ssl_ctx
return None
def start_listening_unix_socket(http_server: HTTPServer) -> None:
address = config.get_option("server.address")
file_name = os.path.expanduser(address[len(UNIX_SOCKET_PREFIX) :])
import tornado.netutil
if hasattr(tornado.netutil, "bind_unix_socket"):
unix_socket = tornado.netutil.bind_unix_socket(file_name)
http_server.add_socket(unix_socket)
else:
_LOGGER.error(
"Unix socket support is not available in this version of Tornado."
)
sys.exit(1)
def start_listening_tcp_socket(http_server: HTTPServer) -> None:
call_count = 0
port = None
while call_count < MAX_PORT_SEARCH_RETRIES:
address = config.get_option("server.address")
port = config.get_option("server.port")
try:
http_server.listen(port, address)
break # It worked! So let's break out of the loop.
except OSError as e:
if e.errno == errno.EADDRINUSE:
if server_port_is_manually_set():
_LOGGER.error("Port %s is already in use", port) # noqa: TRY400
sys.exit(1)
else:
_LOGGER.debug(
"Port %s already in use, trying to use the next one.", port
)
port += 1
config.set_option(
"server.port", port, ConfigOption.STREAMLIT_DEFINITION
)
call_count += 1
else:
raise
if call_count >= MAX_PORT_SEARCH_RETRIES:
raise RetriesExceededError(
f"Cannot start Streamlit server. Port {port} is already in use, and "
f"Streamlit was unable to find a free port after {MAX_PORT_SEARCH_RETRIES} attempts.",
)
class Server:
def __init__(self, main_script_path: str, is_hello: bool) -> None:
"""Create the server. It won't be started yet."""
_set_tornado_log_levels()
self.initialize_mimetypes()
self._main_script_path = main_script_path
# The task that runs the server if an event loop is already running.
# We need to save a reference to it so that it doesn't get
# garbage collected while running.
self._bootstrap_task: asyncio.Task[None] | None = None
# Initialize MediaFileStorage and its associated endpoint
media_file_storage = MemoryMediaFileStorage(MEDIA_ENDPOINT)
MediaFileHandler.initialize_storage(media_file_storage)
uploaded_file_mgr = MemoryUploadedFileManager(UPLOAD_FILE_ENDPOINT)
self._runtime = Runtime(
RuntimeConfig(
script_path=main_script_path,
command_line=None,
media_file_storage=media_file_storage,
uploaded_file_manager=uploaded_file_mgr,
cache_storage_manager=create_default_cache_storage_manager(),
is_hello=is_hello,
session_storage=MemorySessionStorage(
ttl_seconds=config.get_option("server.disconnectedSessionTTL")
),
),
)
self._runtime.stats_mgr.register_provider(media_file_storage)
@classmethod
def initialize_mimetypes(cls) -> None:
"""Ensures that common mime-types are robust against system misconfiguration."""
mimetypes.add_type("text/html", ".html")
mimetypes.add_type("application/javascript", ".js")
mimetypes.add_type("application/javascript", ".mjs")
mimetypes.add_type("text/css", ".css")
mimetypes.add_type("image/webp", ".webp")
def __repr__(self) -> str:
return util.repr_(self)
@property
def main_script_path(self) -> str:
return self._main_script_path
async def start(self) -> None:
"""Start the server.
When this returns, Streamlit is ready to accept new sessions.
"""
_LOGGER.debug("Starting server...")
app = self._create_app()
start_listening(app)
port = config.get_option("server.port")
_LOGGER.debug("Server started on port %s", port)
await self._runtime.start()
@property
def stopped(self) -> Awaitable[None]:
"""A Future that completes when the Server's run loop has exited."""
return self._runtime.stopped
def _create_app(self) -> tornado.web.Application:
"""Create our tornado web app."""
base = config.get_option("server.baseUrlPath")
routes: list[Any] = [
(
make_url_path_regex(base, STREAM_ENDPOINT),
BrowserWebSocketHandler,
{"runtime": self._runtime},
),
(
make_url_path_regex(base, HEALTH_ENDPOINT),
HealthHandler,
{"callback": lambda: self._runtime.is_ready_for_browser_connection},
),
(
make_url_path_regex(base, METRIC_ENDPOINT),
StatsRequestHandler,
{"stats_manager": self._runtime.stats_mgr},
),
(
make_url_path_regex(base, HOST_CONFIG_ENDPOINT),
HostConfigHandler,
),
(
make_url_path_regex(
base,
rf"{UPLOAD_FILE_ENDPOINT}/(?P<session_id>[^/]+)/(?P<file_id>[^/]+)",
),
UploadFileRequestHandler,
{
"file_mgr": self._runtime.uploaded_file_mgr,
"is_active_session": self._runtime.is_active_session,
},
),
(
make_url_path_regex(base, f"{MEDIA_ENDPOINT}/(.*)"),
MediaFileHandler,
{"path": ""},
),
(
make_url_path_regex(base, f"{COMPONENT_ENDPOINT}/(.*)"),
ComponentRequestHandler,
{"registry": self._runtime.component_registry},
),
(
make_url_path_regex(base, f"{BIDI_COMPONENT_ENDPOINT}/(.*)"),
BidiComponentRequestHandler,
{"component_manager": self._runtime.bidi_component_registry},
),
]
if config.get_option("server.scriptHealthCheckEnabled"):
routes.extend(
[
(
make_url_path_regex(base, SCRIPT_HEALTH_CHECK_ENDPOINT),
HealthHandler,
{
"callback": lambda: self._runtime.does_script_run_without_error()
},
)
]
)
if config.get_option("server.enableStaticServing"):
routes.extend(
[
(
make_url_path_regex(base, f"{STATIC_SERVING_ENDPOINT}/(.*)"),
AppStaticFileHandler,
{"path": file_util.get_app_static_dir(self.main_script_path)},
),
]
)
if is_authlib_installed():
from streamlit.web.server.oauth_authlib_routes import (
AuthCallbackHandler,
AuthLoginHandler,
AuthLogoutHandler,
)
routes.extend(
[
(
make_url_path_regex(base, OAUTH2_CALLBACK_ENDPOINT),
AuthCallbackHandler,
{"base_url": base},
),
(
make_url_path_regex(base, AUTH_LOGIN_ENDPOINT),
AuthLoginHandler,
{"base_url": base},
),
(
make_url_path_regex(base, AUTH_LOGOUT_ENDPOINT),
AuthLogoutHandler,
{"base_url": base},
),
]
)
if config.get_option("global.developmentMode"):
_LOGGER.debug("Serving static content from the Node dev server")
else:
static_path = file_util.get_static_dir()
_LOGGER.debug("Serving static content from %s", static_path)
routes.extend(
[
(
# We want to remove paths with a trailing slash, but if the path
# starts with a double slash //, the redirect will point
# the browser to the wrong host.
make_url_path_regex(
base, "(?!/)(.*)", trailing_slash="required"
),
RemoveSlashHandler,
),
(
make_url_path_regex(base, "(.*)"),
StaticFileHandler,
{
"path": f"{static_path}/",
"default_filename": "index.html",
"reserved_paths": [
# These paths are required for identifying
# the base url path.
NEW_HEALTH_ENDPOINT,
HOST_CONFIG_ENDPOINT,
],
},
),
(
make_url_path_regex(base, trailing_slash="prohibited"),
AddSlashHandler,
),
]
)
return tornado.web.Application(
routes,
cookie_secret=get_cookie_secret(),
xsrf_cookies=is_xsrf_enabled(),
# Set the websocket message size. The default value is too low.
websocket_max_message_size=get_max_message_size_bytes(),
**get_tornado_settings(),
)
@property
def browser_is_connected(self) -> bool:
return self._runtime.state == RuntimeState.ONE_OR_MORE_SESSIONS_CONNECTED
@property
def is_running_hello(self) -> bool:
from streamlit.hello import streamlit_app
return self._main_script_path == streamlit_app.__file__
def stop(self) -> None:
cli_util.print_to_cli(" Stopping...", fg="blue")
self._runtime.stop()
def _set_tornado_log_levels() -> None:
if not config.get_option("global.developmentMode"):
# Hide logs unless they're super important.
# Example of stuff we don't care about: 404 about .js.map files.
logging.getLogger("tornado.access").setLevel(logging.ERROR)
logging.getLogger("tornado.application").setLevel(logging.ERROR)
logging.getLogger("tornado.general").setLevel(logging.ERROR)
|
0
|
hf_public_repos/streamlit/lib/streamlit/web
|
hf_public_repos/streamlit/lib/streamlit/web/server/websocket_headers.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from streamlit import runtime
from streamlit.deprecation_util import show_deprecation_warning
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner_utils.script_run_context import get_script_run_ctx
from streamlit.web.server.browser_websocket_handler import BrowserWebSocketHandler
_GET_WEBSOCKET_HEADERS_DEPRECATE_MSG = (
"The `_get_websocket_headers` function is deprecated and will be removed "
"in a future version of Streamlit. Please use `st.context.headers` instead."
)
@gather_metrics("_get_websocket_headers")
def _get_websocket_headers() -> dict[str, str] | None:
"""Return a copy of the HTTP request headers for the current session's
WebSocket connection. If there's no active session, return None instead.
Raise an error if the server is not running.
Note to the intrepid: this is an UNSUPPORTED, INTERNAL API. (We don't have plans
to remove it without a replacement, but we don't consider this a production-ready
function, and its signature may change without a deprecation warning.)
"""
show_deprecation_warning(_GET_WEBSOCKET_HEADERS_DEPRECATE_MSG)
ctx = get_script_run_ctx()
if ctx is None:
return None
session_client = runtime.get_instance().get_client(ctx.session_id)
if session_client is None:
return None
if not isinstance(session_client, BrowserWebSocketHandler):
raise TypeError(
f"SessionClient is not a BrowserWebSocketHandler! ({session_client})"
)
return dict(session_client.request.headers)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/alert.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from typing import TYPE_CHECKING, cast
from streamlit.elements.lib.layout_utils import validate_width
from streamlit.proto.Alert_pb2 import Alert as AlertProto
from streamlit.proto.WidthConfig_pb2 import WidthConfig
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.string_util import clean_text, validate_icon_or_emoji
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
from streamlit.elements.lib.layout_utils import WidthWithoutContent
from streamlit.type_util import SupportsStr
class AlertMixin:
@gather_metrics("error")
def error(
self,
body: SupportsStr,
*, # keyword-only args:
icon: str | None = None,
width: WidthWithoutContent = "stretch",
) -> DeltaGenerator:
"""Display error message.
Parameters
----------
body : str
The text to display as GitHub-flavored Markdown. Syntax
information can be found at: https://github.github.com/gfm.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
icon : str, None
An optional emoji or icon to display next to the alert. If ``icon``
is ``None`` (default), no icon is displayed. If ``icon`` is a
string, the following options are valid:
- A single-character emoji. For example, you can set ``icon="🚨"``
or ``icon="🔥"``. Emoji short codes are not supported.
- An icon from the Material Symbols library (rounded style) in the
format ``":material/icon_name:"`` where "icon_name" is the name
of the icon in snake case.
For example, ``icon=":material/thumb_up:"`` will display the
Thumb Up icon. Find additional icons in the `Material Symbols \
<https://fonts.google.com/icons?icon.set=Material+Symbols&icon.style=Rounded>`_
font library.
- ``"spinner"``: Displays a spinner as an icon.
width : "stretch" or int
The width of the alert element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
Example
-------
>>> import streamlit as st
>>>
>>> st.error('This is an error', icon="🚨")
"""
alert_proto = AlertProto()
alert_proto.icon = validate_icon_or_emoji(icon)
alert_proto.body = clean_text(body)
alert_proto.format = AlertProto.ERROR
validate_width(width)
width_config = WidthConfig()
if isinstance(width, int):
width_config.pixel_width = width
else:
width_config.use_stretch = True
alert_proto.width_config.CopyFrom(width_config)
return self.dg._enqueue("alert", alert_proto)
@gather_metrics("warning")
def warning(
self,
body: SupportsStr,
*, # keyword-only args:
icon: str | None = None,
width: WidthWithoutContent = "stretch",
) -> DeltaGenerator:
"""Display warning message.
Parameters
----------
body : str
The text to display as GitHub-flavored Markdown. Syntax
information can be found at: https://github.github.com/gfm.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
icon : str, None
An optional emoji or icon to display next to the alert. If ``icon``
is ``None`` (default), no icon is displayed. If ``icon`` is a
string, the following options are valid:
- A single-character emoji. For example, you can set ``icon="🚨"``
or ``icon="🔥"``. Emoji short codes are not supported.
- An icon from the Material Symbols library (rounded style) in the
format ``":material/icon_name:"`` where "icon_name" is the name
of the icon in snake case.
For example, ``icon=":material/thumb_up:"`` will display the
Thumb Up icon. Find additional icons in the `Material Symbols \
<https://fonts.google.com/icons?icon.set=Material+Symbols&icon.style=Rounded>`_
font library.
- ``"spinner"``: Displays a spinner as an icon.
width : "stretch" or int
The width of the warning element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
Example
-------
>>> import streamlit as st
>>>
>>> st.warning('This is a warning', icon="⚠️")
"""
alert_proto = AlertProto()
alert_proto.body = clean_text(body)
alert_proto.icon = validate_icon_or_emoji(icon)
alert_proto.format = AlertProto.WARNING
validate_width(width)
width_config = WidthConfig()
if isinstance(width, int):
width_config.pixel_width = width
else:
width_config.use_stretch = True
alert_proto.width_config.CopyFrom(width_config)
return self.dg._enqueue("alert", alert_proto)
@gather_metrics("info")
def info(
self,
body: SupportsStr,
*, # keyword-only args:
icon: str | None = None,
width: WidthWithoutContent = "stretch",
) -> DeltaGenerator:
"""Display an informational message.
Parameters
----------
body : str
The text to display as GitHub-flavored Markdown. Syntax
information can be found at: https://github.github.com/gfm.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
icon : str, None
An optional emoji or icon to display next to the alert. If ``icon``
is ``None`` (default), no icon is displayed. If ``icon`` is a
string, the following options are valid:
- A single-character emoji. For example, you can set ``icon="🚨"``
or ``icon="🔥"``. Emoji short codes are not supported.
- An icon from the Material Symbols library (rounded style) in the
format ``":material/icon_name:"`` where "icon_name" is the name
of the icon in snake case.
For example, ``icon=":material/thumb_up:"`` will display the
Thumb Up icon. Find additional icons in the `Material Symbols \
<https://fonts.google.com/icons?icon.set=Material+Symbols&icon.style=Rounded>`_
font library.
- ``"spinner"``: Displays a spinner as an icon.
width : "stretch" or int
The width of the info element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
Example
-------
>>> import streamlit as st
>>>
>>> st.info('This is a purely informational message', icon="ℹ️")
""" # noqa: RUF002
alert_proto = AlertProto()
alert_proto.body = clean_text(body)
alert_proto.icon = validate_icon_or_emoji(icon)
alert_proto.format = AlertProto.INFO
validate_width(width)
width_config = WidthConfig()
if isinstance(width, int):
width_config.pixel_width = width
else:
width_config.use_stretch = True
alert_proto.width_config.CopyFrom(width_config)
return self.dg._enqueue("alert", alert_proto)
@gather_metrics("success")
def success(
self,
body: SupportsStr,
*, # keyword-only args:
icon: str | None = None,
width: WidthWithoutContent = "stretch",
) -> DeltaGenerator:
"""Display a success message.
Parameters
----------
body : str
The text to display as GitHub-flavored Markdown. Syntax
information can be found at: https://github.github.com/gfm.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
icon : str, None
An optional emoji or icon to display next to the alert. If ``icon``
is ``None`` (default), no icon is displayed. If ``icon`` is a
string, the following options are valid:
- A single-character emoji. For example, you can set ``icon="🚨"``
or ``icon="🔥"``. Emoji short codes are not supported.
- An icon from the Material Symbols library (rounded style) in the
format ``":material/icon_name:"`` where "icon_name" is the name
of the icon in snake case.
For example, ``icon=":material/thumb_up:"`` will display the
Thumb Up icon. Find additional icons in the `Material Symbols \
<https://fonts.google.com/icons?icon.set=Material+Symbols&icon.style=Rounded>`_
font library.
- ``"spinner"``: Displays a spinner as an icon.
width : "stretch" or int
The width of the success element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
Example
-------
>>> import streamlit as st
>>>
>>> st.success('This is a success message!', icon="✅")
"""
alert_proto = AlertProto()
alert_proto.body = clean_text(body)
alert_proto.icon = validate_icon_or_emoji(icon)
alert_proto.format = AlertProto.SUCCESS
validate_width(width)
width_config = WidthConfig()
if isinstance(width, int):
width_config.pixel_width = width
else:
width_config.use_stretch = True
alert_proto.width_config.CopyFrom(width_config)
return self.dg._enqueue("alert", alert_proto)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/__init__.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/write.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import dataclasses
import inspect
import types
from collections import ChainMap, UserDict, UserList
from collections.abc import (
AsyncGenerator,
Callable,
Generator,
ItemsView,
Iterable,
KeysView,
ValuesView,
)
from io import StringIO
from typing import (
TYPE_CHECKING,
Any,
Final,
cast,
)
from streamlit import dataframe_util, type_util
from streamlit.errors import StreamlitAPIException
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.string_util import (
is_mem_address_str,
max_char_sequence,
)
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
# Special methods:
HELP_TYPES: Final[tuple[type[Any], ...]] = (
types.BuiltinFunctionType,
types.BuiltinMethodType,
types.FunctionType,
types.MethodType,
types.ModuleType,
)
class StreamingOutput(list[Any]):
pass
class WriteMixin:
@gather_metrics("write_stream")
def write_stream(
self,
stream: Callable[..., Any]
| Generator[Any, Any, Any]
| Iterable[Any]
| AsyncGenerator[Any, Any],
*,
cursor: str | None = None,
) -> list[Any] | str:
r"""Stream a generator, iterable, or stream-like sequence to the app.
``st.write_stream`` iterates through the given sequences and writes all
chunks to the app. String chunks will be written using a typewriter effect.
Other data types will be written using ``st.write``.
Parameters
----------
stream : Callable, Generator, Iterable, OpenAI Stream, or LangChain Stream
The generator or iterable to stream.
If you pass an async generator, Streamlit will internally convert
it to a sync generator. If the generator depends on a cached object
with async references, this can raise an error.
.. note::
To use additional LLM libraries, you can create a wrapper to
manually define a generator function and include custom output
parsing.
cursor : str or None
A string to append to text as it's being written. If this is
``None`` (default), no cursor is shown. Otherwise, the string is
rendered as Markdown and appears as a cursor at the end of the
streamed text. For example, you can use an emoji, emoji shortcode,
or Material icon.
The first line of the cursor string can contain GitHub-flavored
Markdown of the following types: Bold, Italics, Strikethroughs,
Inline Code, Links, and Images. Images display like icons, with a
max height equal to the font height. If you pass a multiline
string, additional lines display after the text with the full
Markdown rendering capabilities of ``st.markdown``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
Returns
-------
str or list
The full response. If the streamed output only contains text, this
is a string. Otherwise, this is a list of all the streamed objects.
The return value is fully compatible as input for ``st.write``.
Example
-------
You can pass an OpenAI stream as shown in our tutorial, `Build a \
basic LLM chat app <https://docs.streamlit.io/develop/tutorials/llms\
/build-conversational-apps#build-a-chatgpt-like-app>`_. Alternatively,
you can pass a generic generator function as input:
>>> import time
>>> import numpy as np
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> _LOREM_IPSUM = \"\"\"
>>> Lorem ipsum dolor sit amet, **consectetur adipiscing** elit, sed do eiusmod tempor
>>> incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
>>> nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
>>> \"\"\"
>>>
>>>
>>> def stream_data():
>>> for word in _LOREM_IPSUM.split(" "):
>>> yield word + " "
>>> time.sleep(0.02)
>>>
>>> yield pd.DataFrame(
>>> np.random.randn(5, 10),
>>> columns=["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"],
>>> )
>>>
>>> for word in _LOREM_IPSUM.split(" "):
>>> yield word + " "
>>> time.sleep(0.02)
>>>
>>>
>>> if st.button("Stream data"):
>>> st.write_stream(stream_data)
.. output::
https://doc-write-stream-data.streamlit.app/
height: 550px
"""
# Just apply some basic checks for common iterable types that should
# not be passed in here.
if isinstance(stream, str) or dataframe_util.is_dataframe_like(stream):
raise StreamlitAPIException(
"`st.write_stream` expects a generator or stream-like object as input "
f"not {type(stream)}. Please use `st.write` instead for "
"this data type."
)
cursor_str = cursor or ""
stream_container: DeltaGenerator | None = None
streamed_response: str = ""
written_content: list[Any] = StreamingOutput()
def flush_stream_response() -> None:
"""Write the full response to the app."""
nonlocal streamed_response
nonlocal stream_container
if streamed_response and stream_container:
# Replace the stream_container element the full response
stream_container.markdown(streamed_response)
written_content.append(streamed_response)
stream_container = None
streamed_response = ""
# Make sure we have a generator and not just a generator function.
if inspect.isgeneratorfunction(stream) or inspect.isasyncgenfunction(stream):
stream = stream()
# If the stream is an async generator, convert it to a sync generator:
if inspect.isasyncgen(stream):
stream = type_util.async_generator_to_sync(stream)
try:
iter(stream) # type: ignore
except TypeError as exc:
raise StreamlitAPIException(
f"The provided input (type: {type(stream)}) cannot be iterated. "
"Please make sure that it is a generator, generator function or iterable."
) from exc
# Iterate through the generator and write each chunk to the app
# with a type writer effect.
for chunk in stream: # type: ignore
if type_util.is_openai_chunk(chunk):
# Try to convert OpenAI chat completion chunk to a string:
try:
if len(chunk.choices) == 0 or chunk.choices[0].delta is None:
# The choices list can be empty. E.g. when using the
# AzureOpenAI client, the first chunk will always be empty.
chunk = "" # noqa: PLW2901
else:
chunk = chunk.choices[0].delta.content or "" # noqa: PLW2901
except AttributeError as err:
raise StreamlitAPIException(
"Failed to parse the OpenAI ChatCompletionChunk. "
"The most likely cause is a change of the chunk object structure "
"due to a recent OpenAI update. You might be able to fix this "
"by downgrading the OpenAI library or upgrading Streamlit. Also, "
"please report this issue to: https://github.com/streamlit/streamlit/issues."
) from err
if type_util.is_type(chunk, "langchain_core.messages.ai.AIMessageChunk"):
# Try to convert LangChain message chunk to a string:
try:
chunk = chunk.content or "" # noqa: PLW2901 # type: ignore[possibly-unbound-attribute]
except AttributeError as err:
raise StreamlitAPIException(
"Failed to parse the LangChain AIMessageChunk. "
"The most likely cause is a change of the chunk object structure "
"due to a recent LangChain update. You might be able to fix this "
"by downgrading the OpenAI library or upgrading Streamlit. Also, "
"please report this issue to: https://github.com/streamlit/streamlit/issues."
) from err
if isinstance(chunk, str):
if not chunk:
# Empty strings can be ignored
continue
first_text = False
if not stream_container:
stream_container = self.dg.empty()
first_text = True
streamed_response += chunk
# Only add the streaming symbol on the second text chunk
stream_container.markdown(
streamed_response + ("" if first_text else cursor_str),
)
elif callable(chunk):
flush_stream_response()
chunk()
else:
flush_stream_response()
self.write(chunk)
written_content.append(chunk)
flush_stream_response()
if not written_content:
# If nothing was streamed, return an empty string.
return ""
if len(written_content) == 1 and isinstance(written_content[0], str):
# If the output only contains a single string, return it as a string
return written_content[0]
# Otherwise return it as a list of write-compatible objects
return written_content
@gather_metrics("write")
def write(self, *args: Any, unsafe_allow_html: bool = False) -> None:
"""Displays arguments in the app.
This is the Swiss Army knife of Streamlit commands: it does different
things depending on what you throw at it. Unlike other Streamlit
commands, ``st.write()`` has some unique properties:
- You can pass in multiple arguments, all of which will be displayed.
- Its behavior depends on the input type(s).
Parameters
----------
*args : any
One or many objects to display in the app.
.. list-table:: Each type of argument is handled as follows:
:header-rows: 1
* - Type
- Handling
* - ``str``
- Uses ``st.markdown()``.
* - dataframe-like, ``dict``, or ``list``
- Uses ``st.dataframe()``.
* - ``Exception``
- Uses ``st.exception()``.
* - function, module, or class
- Uses ``st.help()``.
* - ``DeltaGenerator``
- Uses ``st.help()``.
* - Altair chart
- Uses ``st.altair_chart()``.
* - Bokeh figure
- Uses ``st.bokeh_chart()``.
* - Graphviz graph
- Uses ``st.graphviz_chart()``.
* - Keras model
- Converts model and uses ``st.graphviz_chart()``.
* - Matplotlib figure
- Uses ``st.pyplot()``.
* - Plotly figure
- Uses ``st.plotly_chart()``.
* - ``PIL.Image``
- Uses ``st.image()``.
* - generator or stream (like ``openai.Stream``)
- Uses ``st.write_stream()``.
* - SymPy expression
- Uses ``st.latex()``.
* - An object with ``._repr_html()``
- Uses ``st.html()``.
* - Database cursor
- Displays DB API 2.0 cursor results in a table.
* - Any
- Displays ``str(arg)`` as inline code.
unsafe_allow_html : bool
Whether to render HTML within ``*args``. This only applies to
strings or objects falling back on ``_repr_html_()``. If this is
``False`` (default), any HTML tags found in ``body`` will be
escaped and therefore treated as raw text. If this is ``True``, any
HTML expressions within ``body`` will be rendered.
Adding custom HTML to your app impacts safety, styling, and
maintainability.
.. note::
If you only want to insert HTML or CSS without Markdown text,
we recommend using ``st.html`` instead.
Returns
-------
None
Examples
--------
Its basic use case is to draw Markdown-formatted text, whenever the
input is a string:
>>> import streamlit as st
>>>
>>> st.write("Hello, *World!* :sunglasses:")
.. output::
https://doc-write1.streamlit.app/
height: 150px
As mentioned earlier, ``st.write()`` also accepts other data formats, such as
numbers, data frames, styled data frames, and assorted objects:
>>> import streamlit as st
>>> import pandas as pd
>>>
>>> st.write(1234)
>>> st.write(
... pd.DataFrame(
... {
... "first column": [1, 2, 3, 4],
... "second column": [10, 20, 30, 40],
... }
... )
... )
.. output::
https://doc-write2.streamlit.app/
height: 350px
Finally, you can pass in multiple arguments to do things like:
>>> import streamlit as st
>>>
>>> st.write("1 + 1 = ", 2)
>>> st.write("Below is a DataFrame:", data_frame, "Above is a dataframe.")
.. output::
https://doc-write3.streamlit.app/
height: 410px
Oh, one more thing: ``st.write`` accepts chart objects too! For example:
>>> import altair as alt
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(rng(0).standard_normal((200, 3)), columns=["a", "b", "c"])
>>> chart = (
... alt.Chart(df)
... .mark_circle()
... .encode(x="a", y="b", size="c", color="c", tooltip=["a", "b", "c"])
... )
>>>
>>> st.write(chart)
.. output::
https://doc-vega-lite-chart.streamlit.app/
height: 300px
"""
if len(args) == 1 and isinstance(args[0], str):
# Optimization: If there is only one arg, and it's a string,
# we can just call markdown directly and skip the buffer logic.
# This also prevents unnecessary usage of `st.empty()`.
# This covers > 80% of all `st.write` uses.
self.dg.markdown(args[0], unsafe_allow_html=unsafe_allow_html)
return
string_buffer: list[str] = []
# This bans some valid cases like: e = st.empty(); e.write("a", "b").
# BUT: 1) such cases are rare, 2) this rule is easy to understand,
# and 3) this rule should be removed once we have st.container()
if not self.dg._is_top_level and len(args) > 1:
raise StreamlitAPIException(
"Cannot replace a single element with multiple elements.\n\n"
"The `write()` method only supports multiple elements when "
"inserting elements rather than replacing. That is, only "
"when called as `st.write()` or `st.sidebar.write()`."
)
def flush_buffer() -> None:
if string_buffer:
text_content = " ".join(string_buffer)
# The usage of empty here prevents
# some grey out effects:
text_container = self.dg.empty()
text_container.markdown(
text_content,
unsafe_allow_html=unsafe_allow_html,
)
string_buffer[:] = []
for arg in args:
# Order matters!
if isinstance(arg, str):
string_buffer.append(arg)
elif isinstance(arg, StreamingOutput):
flush_buffer()
for item in arg:
if callable(item):
flush_buffer()
item()
else:
self.write(item, unsafe_allow_html=unsafe_allow_html)
elif isinstance(arg, Exception):
flush_buffer()
self.dg.exception(arg)
elif type_util.is_delta_generator(arg):
flush_buffer()
self.dg.help(arg)
elif dataframe_util.is_dataframe_like(arg):
flush_buffer()
self.dg.dataframe(arg)
elif type_util.is_altair_chart(arg):
flush_buffer()
self.dg.altair_chart(arg)
elif type_util.is_type(arg, "matplotlib.figure.Figure"):
flush_buffer()
self.dg.pyplot(arg)
elif type_util.is_plotly_chart(arg):
flush_buffer()
self.dg.plotly_chart(arg)
elif type_util.is_type(arg, "bokeh.plotting.figure.Figure"):
flush_buffer()
self.dg.bokeh_chart(arg)
elif type_util.is_graphviz_chart(arg):
flush_buffer()
self.dg.graphviz_chart(arg)
elif type_util.is_sympy_expression(arg):
flush_buffer()
self.dg.latex(arg)
elif type_util.is_pillow_image(arg):
flush_buffer()
self.dg.image(arg)
elif type_util.is_keras_model(arg):
from tensorflow.python.keras.utils import ( # type: ignore
vis_utils,
)
flush_buffer()
dot = vis_utils.model_to_dot(arg)
self.dg.graphviz_chart(dot.to_string())
elif (
isinstance(
arg,
(
dict,
list,
map,
enumerate,
types.MappingProxyType,
UserDict,
ChainMap,
UserList,
ItemsView,
KeysView,
ValuesView,
),
)
or type_util.is_custom_dict(arg)
or type_util.is_namedtuple(arg)
or type_util.is_pydantic_model(arg)
):
flush_buffer()
self.dg.json(arg)
elif type_util.is_pydeck(arg):
flush_buffer()
self.dg.pydeck_chart(arg)
elif isinstance(arg, StringIO):
flush_buffer()
self.dg.markdown(arg.getvalue())
elif (
inspect.isgenerator(arg)
or inspect.isgeneratorfunction(arg)
or inspect.isasyncgenfunction(arg)
or inspect.isasyncgen(arg)
or type_util.is_type(arg, "openai.Stream")
):
flush_buffer()
self.write_stream(arg)
elif isinstance(arg, HELP_TYPES) or dataclasses.is_dataclass(arg):
flush_buffer()
self.dg.help(arg)
elif inspect.isclass(arg):
flush_buffer()
# We cast arg to type here to appease mypy, due to bug in mypy:
# https://github.com/python/mypy/issues/12933
self.dg.help(cast("type", arg))
elif unsafe_allow_html and type_util.has_callable_attr(arg, "_repr_html_"):
self.dg.html(arg._repr_html_())
elif type_util.has_callable_attr(
arg, "to_pandas"
) or type_util.has_callable_attr(arg, "__dataframe__"):
# This object can very likely be converted to a DataFrame
# using the to_pandas, to_arrow, or the dataframe interchange
# protocol.
flush_buffer()
self.dg.dataframe(arg)
else:
stringified_arg = str(arg)
if is_mem_address_str(stringified_arg):
flush_buffer()
self.dg.help(arg)
elif "\n" in stringified_arg:
# With a multi-line string, use a preformatted block
# To fully escape backticks, we wrap with backticks larger than
# the largest sequence of backticks in the string.
backtick_count = max(3, max_char_sequence(stringified_arg, "`") + 1)
backtick_wrapper = "`" * backtick_count
string_buffer.append(
f"{backtick_wrapper}\n{stringified_arg}\n{backtick_wrapper}"
)
else:
# With a single-line string, use a preformatted text
# To fully escape backticks, we wrap with backticks larger than
# the largest sequence of backticks in the string.
backtick_count = max_char_sequence(stringified_arg, "`") + 1
backtick_wrapper = "`" * backtick_count
string_buffer.append(
f"{backtick_wrapper}{stringified_arg}{backtick_wrapper}"
)
flush_buffer()
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/code.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import re
from typing import TYPE_CHECKING, cast
from streamlit.elements.lib.layout_utils import (
Height,
LayoutConfig,
Width,
validate_height,
validate_width,
)
from streamlit.proto.Code_pb2 import Code as CodeProto
from streamlit.runtime.metrics_util import gather_metrics
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
from streamlit.type_util import SupportsStr
class CodeMixin:
@gather_metrics("code")
def code(
self,
body: SupportsStr,
language: str | None = "python",
*,
line_numbers: bool = False,
wrap_lines: bool = False,
height: Height | None = "content",
width: Width = "stretch",
) -> DeltaGenerator:
"""Display a code block with optional syntax highlighting.
Parameters
----------
body : str
The string to display as code or monospace text.
language : str or None
The language that the code is written in, for syntax highlighting.
This defaults to ``"python"``. If this is ``None``, the code will
be plain, monospace text.
For a list of available ``language`` values, see
`react-syntax-highlighter
<https://github.com/react-syntax-highlighter/react-syntax-highlighter/blob/master/AVAILABLE_LANGUAGES_PRISM.MD>`_
on GitHub.
line_numbers : bool
An optional boolean indicating whether to show line numbers to the
left of the code block. This defaults to ``False``.
wrap_lines : bool
An optional boolean indicating whether to wrap lines. This defaults
to ``False``.
height : "content", "stretch", or int
The height of the code block element. This can be one of the following:
- ``"content"`` (default): The height of the element matches the
height of its content.
- ``"stretch"``: The height of the element matches the height of
its content or the height of the parent container, whichever is
larger. If the element is not in a parent container, the height
of the element matches the height of its content.
- An integer specifying the height in pixels: The element has a
fixed height. If the content is larger than the specified
height, scrolling is enabled.
.. note::
Use scrolling containers sparingly. If you use scrolling
containers, avoid heights that exceed 500 pixels. Otherwise,
the scroll surface of the container might cover the majority of
the screen on mobile devices, which makes it hard to scroll the
rest of the app.
width : "stretch", "content", or int
The width of the code block element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- ``"content"``: The width of the element matches the width of its
content, but doesn't exceed the width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
Examples
--------
>>> import streamlit as st
>>>
>>> code = '''def hello():
... print("Hello, Streamlit!")'''
>>> st.code(code, language="python")
.. output::
https://doc-code.streamlit.app/
height: 220px
>>> import streamlit as st
>>> code = '''Is it a crown or boat?
... ii
... iiiiii
... WWw .iiiiiiii. ...:
... WWWWWWw .iiiiiiiiiiii. ........
... WWWWWWWWWWw iiiiiiiiiiiiiiii ...........
... WWWWWWWWWWWWWWwiiiiiiiiiiiiiiiii............
... WWWWWWWWWWWWWWWWWWwiiiiiiiiiiiiii.........
... WWWWWWWWWWWWWWWWWWWWWWwiiiiiiiiii.......
... WWWWWWWWWWWWWWWWWWWWWWWWWWwiiiiiii....
... WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWwiiii.
... -MMMWWWWWWWWWWWWWWWWWWWWWWMMM-
... '''
>>> st.code(code, language=None)
.. output::
https://doc-code-ascii.streamlit.app/
height: 380px
"""
code_proto = CodeProto()
code_proto.code_text = re.sub(r"\n\Z", "", re.sub(r"\A\n", "", str(body)))
code_proto.language = language or "plaintext"
code_proto.show_line_numbers = line_numbers
code_proto.wrap_lines = wrap_lines
if height is None:
height = "content"
else:
validate_height(height, allow_content=True)
validate_width(width, allow_content=True)
layout_config = LayoutConfig(height=height, width=width)
return self.dg._enqueue("code", code_proto, layout_config=layout_config)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/map.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
"""A wrapper for simple PyDeck scatter charts."""
from __future__ import annotations
import copy
import json
from typing import TYPE_CHECKING, Any, Final, cast
from streamlit import config, dataframe_util
from streamlit.deprecation_util import (
make_deprecated_name_warning,
show_deprecation_warning,
)
from streamlit.elements import deck_gl_json_chart
from streamlit.elements.lib.color_util import (
Color,
IntColorTuple,
is_color_like,
to_int_color_tuple,
)
from streamlit.elements.lib.layout_utils import (
HeightWithoutContent,
LayoutConfig,
WidthWithoutContent,
validate_height,
validate_width,
)
from streamlit.errors import StreamlitAPIException
from streamlit.proto.DeckGlJsonChart_pb2 import DeckGlJsonChart as DeckGlJsonChartProto
from streamlit.runtime.metrics_util import gather_metrics
if TYPE_CHECKING:
from collections.abc import Collection
from pandas import DataFrame
from streamlit.dataframe_util import Data
from streamlit.delta_generator import DeltaGenerator
# Map used as the basis for st.map.
_DEFAULT_MAP: Final[dict[str, Any]] = dict(deck_gl_json_chart.EMPTY_MAP)
# Other default parameters for st.map.
_DEFAULT_LAT_COL_NAMES: Final = {"lat", "latitude", "LAT", "LATITUDE"}
_DEFAULT_LON_COL_NAMES: Final = {"lon", "longitude", "LON", "LONGITUDE"}
_DEFAULT_COLOR: Final = (200, 30, 0, 160)
_DEFAULT_SIZE: Final = 100
_DEFAULT_ZOOM_LEVEL: Final = 12
_ZOOM_LEVELS: Final = [
360,
180,
90,
45,
22.5,
11.25,
5.625,
2.813,
1.406,
0.703,
0.352,
0.176,
0.088,
0.044,
0.022,
0.011,
0.005,
0.003,
0.001,
0.0005,
0.00025,
]
class MapMixin:
@gather_metrics("map")
def map(
self,
data: Data = None,
*,
latitude: str | None = None,
longitude: str | None = None,
color: None | str | Color = None,
size: None | str | float = None,
zoom: int | None = None,
width: WidthWithoutContent = "stretch",
height: HeightWithoutContent = 500,
use_container_width: bool | None = None,
) -> DeltaGenerator:
"""Display a map with a scatterplot overlaid onto it.
This is a wrapper around ``st.pydeck_chart`` to quickly create
scatterplot charts on top of a map, with auto-centering and auto-zoom.
When using this command, a service called Carto_ provides the map tiles to render
map content. If you're using advanced PyDeck features you may need to obtain
an API key from Carto first. You can do that as
``pydeck.Deck(api_keys={"carto": YOUR_KEY})`` or by setting the CARTO_API_KEY
environment variable. See `PyDeck's documentation`_ for more information.
Another common provider for map tiles is Mapbox_. If you prefer to use that,
you'll need to create an account at https://mapbox.com and specify your Mapbox
key when creating the ``pydeck.Deck`` object. You can do that as
``pydeck.Deck(api_keys={"mapbox": YOUR_KEY})`` or by setting the MAPBOX_API_KEY
environment variable.
.. _Carto: https://carto.com
.. _Mapbox: https://mapbox.com
.. _PyDeck's documentation: https://deckgl.readthedocs.io/en/latest/deck.html
Carto and Mapbox are third-party products and Streamlit accepts no responsibility
or liability of any kind for Carto or Mapbox, or for any content or information
made available by Carto or Mapbox. The use of Carto or Mapbox is governed by
their respective Terms of Use.
Parameters
----------
data : Anything supported by st.dataframe
The data to be plotted.
latitude : str or None
The name of the column containing the latitude coordinates of
the datapoints in the chart.
If None, the latitude data will come from any column named 'lat',
'latitude', 'LAT', or 'LATITUDE'.
longitude : str or None
The name of the column containing the longitude coordinates of
the datapoints in the chart.
If None, the longitude data will come from any column named 'lon',
'longitude', 'LON', or 'LONGITUDE'.
color : str or tuple or None
The color of the circles representing each datapoint.
Can be:
- None, to use the default color.
- A hex string like "#ffaa00" or "#ffaa0088".
- An RGB or RGBA tuple with the red, green, blue, and alpha
components specified as ints from 0 to 255 or floats from 0.0 to
1.0.
- The name of the column to use for the color. Cells in this column
should contain colors represented as a hex string or color tuple,
as described above.
size : str or float or None
The size of the circles representing each point, in meters.
This can be:
- None, to use the default size.
- A number like 100, to specify a single size to use for all
datapoints.
- The name of the column to use for the size. This allows each
datapoint to be represented by a circle of a different size.
zoom : int
Zoom level as specified in
https://wiki.openstreetmap.org/wiki/Zoom_levels.
width : "stretch" or int
The width of the chart element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
height : "stretch" or int
The height of the chart element. This can be one of the following:
- An integer specifying the height in pixels: The element has a
fixed height. If the content is larger than the specified
height, scrolling is enabled. This is ``500`` by default.
- ``"stretch"``: The height of the element matches the height of
its content or the height of the parent container, whichever is
larger. If the element is not in a parent container, the height
of the element matches the height of its content.
use_container_width : bool or None
Whether to override the map's native width with the width of
the parent container. This can be one of the following:
- ``None`` (default): Streamlit will use the map's default behavior.
- ``True``: Streamlit sets the width of the map to match the
width of the parent container.
- ``False``: Streamlit sets the width of the map to fit its
contents according to the plotting library, up to the width of
the parent container.
.. deprecated::
``use_container_width`` is deprecated and will be removed in a
future release. For ``use_container_width=True``, use
``width="stretch"``.
Examples
--------
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(
>>> rng(0).standard_normal((1000, 2)) / [50, 50] + [37.76, -122.4],
>>> columns=["lat", "lon"],
>>> )
>>>
>>> st.map(df)
.. output::
https://doc-map.streamlit.app/
height: 600px
You can also customize the size and color of the datapoints:
>>> st.map(df, size=20, color="#0044ff")
And finally, you can choose different columns to use for the latitude
and longitude components, as well as set size and color of each
datapoint dynamically based on other columns:
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(
... {
... "col1": rng(0).standard_normal(1000) / 50 + 37.76,
... "col2": rng(1).standard_normal(1000) / 50 + -122.4,
... "col3": rng(2).standard_normal(1000) * 100,
... "col4": rng(3).standard_normal((1000, 4)).tolist(),
... }
... )
>>>
>>> st.map(df, latitude="col1", longitude="col2", size="col3", color="col4")
.. output::
https://doc-map-color.streamlit.app/
height: 600px
"""
# Handle use_container_width deprecation (for elements that already had width parameter)
if use_container_width is not None:
show_deprecation_warning(
make_deprecated_name_warning(
"use_container_width",
"width",
"2025-12-31",
"For `use_container_width=True`, use `width='stretch'`. "
"For `use_container_width=False`, specify an integer width.",
include_st_prefix=False,
),
show_in_browser=False,
)
if use_container_width:
width = "stretch"
# For use_container_width=False, preserve any integer width that was set.
validate_width(width, allow_content=False)
validate_height(height, allow_content=False)
map_proto = DeckGlJsonChartProto()
deck_gl_json = to_deckgl_json(data, latitude, longitude, size, color, zoom)
marshall(map_proto, deck_gl_json)
layout_config = LayoutConfig(width=width, height=height)
return self.dg._enqueue(
"deck_gl_json_chart", map_proto, layout_config=layout_config
)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
def to_deckgl_json(
data: Data,
lat: str | None,
lon: str | None,
size: None | str | float,
color: None | str | Collection[float],
zoom: int | None,
) -> str:
if data is None:
return json.dumps(_DEFAULT_MAP)
# TODO(harahu): iterables don't have the empty attribute. This is either
# a bug, or the documented data type is too broad. One or the other
# should be addressed
if hasattr(data, "empty") and data.empty:
return json.dumps(_DEFAULT_MAP)
df = dataframe_util.convert_anything_to_pandas_df(data)
lat_col_name = _get_lat_or_lon_col_name(df, "latitude", lat, _DEFAULT_LAT_COL_NAMES)
lon_col_name = _get_lat_or_lon_col_name(
df, "longitude", lon, _DEFAULT_LON_COL_NAMES
)
size_arg, size_col_name = _get_value_and_col_name(df, size, _DEFAULT_SIZE)
color_arg, color_col_name = _get_value_and_col_name(df, color, _DEFAULT_COLOR)
# Drop columns we're not using.
# (Sort for tests)
used_columns = sorted(
[
c
for c in {lat_col_name, lon_col_name, size_col_name, color_col_name}
if c is not None
]
)
df = df[used_columns]
converted_color_arg = _convert_color_arg_or_column(df, color_arg, color_col_name)
zoom, center_lat, center_lon = _get_viewport_details(
df, lat_col_name, lon_col_name, zoom
)
default = copy.deepcopy(_DEFAULT_MAP)
default["initialViewState"]["latitude"] = center_lat
default["initialViewState"]["longitude"] = center_lon
default["initialViewState"]["zoom"] = zoom
default["layers"] = [
{
"@@type": "ScatterplotLayer",
"getPosition": f"@@=[{lon_col_name}, {lat_col_name}]",
"getRadius": size_arg,
"radiusMinPixels": 3,
"radiusUnits": "meters",
"getFillColor": converted_color_arg,
"data": df.to_dict("records"),
}
]
return json.dumps(default)
def _get_lat_or_lon_col_name(
data: DataFrame,
human_readable_name: str,
col_name_from_user: str | None,
default_col_names: set[str],
) -> str:
"""Returns the column name to be used for latitude or longitude."""
if isinstance(col_name_from_user, str) and col_name_from_user in data.columns:
col_name = col_name_from_user
else:
# Try one of the default col_names:
candidate_col_name = None
for c in default_col_names:
if c in data.columns:
candidate_col_name = c
break
if candidate_col_name is None:
formatted_allowed_col_name = ", ".join(map(repr, sorted(default_col_names)))
formmated_col_names = ", ".join(map(repr, list(data.columns)))
raise StreamlitAPIException(
f"Map data must contain a {human_readable_name} column named: "
f"{formatted_allowed_col_name}. Existing columns: {formmated_col_names}"
)
col_name = candidate_col_name
# Check that the column is well-formed.
# IMPLEMENTATION NOTE: We can't use isnull().values.any() because .values can return
# ExtensionArrays, which don't have a .any() method.
# (Read about ExtensionArrays here: # https://pandas.pydata.org/community/blog/extension-arrays.html)
# However, after a performance test I found the solution below runs basically as
# fast as .values.any().
if any(data[col_name].isna().array):
raise StreamlitAPIException(
f"Column {col_name} is not allowed to contain null values, such "
"as NaN, NaT, or None."
)
return col_name
def _get_value_and_col_name(
data: DataFrame,
value_or_name: Any,
default_value: Any,
) -> tuple[str, str | None]:
"""Take a value_or_name passed in by the Streamlit developer and return a PyDeck
argument and column name for that property.
This is used for the size and color properties of the chart.
Example:
- If the user passes size=None, this returns the default size value and no column.
- If the user passes size=42, this returns 42 and no column.
- If the user passes size="my_col_123", this returns "@@=my_col_123" and "my_col_123".
"""
pydeck_arg: str
if isinstance(value_or_name, str) and value_or_name in data.columns:
col_name = value_or_name
pydeck_arg = f"@@={col_name}"
else:
col_name = None
pydeck_arg = default_value if value_or_name is None else value_or_name
return pydeck_arg, col_name
def _convert_color_arg_or_column(
data: DataFrame,
color_arg: str,
color_col_name: str | None,
) -> None | str | IntColorTuple:
"""Converts color to a format accepted by PyDeck.
For example:
- If color_arg is "#fff", then returns (255, 255, 255, 255).
- If color_col_name is "my_col_123", then it converts everything in column my_col_123 to
an accepted color format such as (0, 100, 200, 255).
NOTE: This function mutates the data argument.
"""
color_arg_out: None | str | IntColorTuple = None
if color_col_name is not None:
# Convert color column to the right format.
if len(data[color_col_name]) > 0 and is_color_like(data[color_col_name].iat[0]):
# Use .loc[] to avoid a SettingWithCopyWarning in some cases.
data.loc[:, color_col_name] = data.loc[:, color_col_name].map(
to_int_color_tuple
)
else:
raise StreamlitAPIException(
f'Column "{color_col_name}" does not appear to contain valid colors.'
)
color_arg_out = color_arg
elif color_arg is not None:
color_arg_out = to_int_color_tuple(color_arg)
return color_arg_out
def _get_viewport_details(
data: DataFrame, lat_col_name: str, lon_col_name: str, zoom: int | None
) -> tuple[int, float, float]:
"""Auto-set viewport when not fully specified by user."""
min_lat = data[lat_col_name].min()
max_lat = data[lat_col_name].max()
min_lon = data[lon_col_name].min()
max_lon = data[lon_col_name].max()
center_lat = (max_lat + min_lat) / 2.0
center_lon = (max_lon + min_lon) / 2.0
range_lon = abs(max_lon - min_lon)
range_lat = abs(max_lat - min_lat)
if zoom is None:
longitude_distance = max(range_lat, range_lon)
zoom = _get_zoom_level(longitude_distance)
return zoom, center_lat, center_lon
def _get_zoom_level(distance: float) -> int:
"""Get the zoom level for a given distance in degrees.
See https://wiki.openstreetmap.org/wiki/Zoom_levels for reference.
Parameters
----------
distance : float
How many degrees of longitude should fit in the map.
Returns
-------
int
The zoom level, from 0 to 20.
"""
for i in range(len(_ZOOM_LEVELS) - 1):
if _ZOOM_LEVELS[i + 1] < distance <= _ZOOM_LEVELS[i]:
return i
# For small number of points the default zoom level will be used.
return _DEFAULT_ZOOM_LEVEL
def marshall(
pydeck_proto: DeckGlJsonChartProto,
pydeck_json: str,
) -> None:
"""Marshall a map proto with the given pydeck JSON specification.
Layout configuration (width, height, etc.) is handled by the LayoutConfig
system and not through proto fields.
"""
pydeck_proto.json = pydeck_json
pydeck_proto.id = ""
mapbox_token = config.get_option("mapbox.token")
if mapbox_token:
pydeck_proto.mapbox_token = mapbox_token
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/graphviz_chart.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
"""Streamlit support for GraphViz charts."""
from __future__ import annotations
from typing import TYPE_CHECKING, TypeAlias, Union, cast
from streamlit import type_util
from streamlit.deprecation_util import (
make_deprecated_name_warning,
show_deprecation_warning,
)
from streamlit.elements.lib.layout_utils import (
Height,
LayoutConfig,
Width,
validate_height,
validate_width,
)
from streamlit.errors import StreamlitAPIException
from streamlit.proto.GraphVizChart_pb2 import GraphVizChart as GraphVizChartProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.util import calc_md5
if TYPE_CHECKING:
import graphviz
from streamlit.delta_generator import DeltaGenerator
FigureOrDot: TypeAlias = Union[
"graphviz.Graph", "graphviz.Digraph", "graphviz.Source", str
]
class GraphvizMixin:
@gather_metrics("graphviz_chart")
def graphviz_chart(
self,
figure_or_dot: FigureOrDot,
use_container_width: bool | None = None,
*, # keyword-only arguments:
width: Width = "content",
height: Height = "content",
) -> DeltaGenerator:
"""Display a graph using the dagre-d3 library.
.. Important::
You must install ``graphviz>=0.19.0`` to use this command. You can
install all charting dependencies (except Bokeh) as an extra with
Streamlit:
.. code-block:: shell
pip install streamlit[charts]
Parameters
----------
figure_or_dot : graphviz.dot.Graph, graphviz.dot.Digraph, graphviz.sources.Source, str
The Graphlib graph object or dot string to display
use_container_width : bool
Whether to override the figure's native width with the width of
the parent container. If ``use_container_width`` is ``False``
(default), Streamlit sets the width of the chart to fit its contents
according to the plotting library, up to the width of the parent
container. If ``use_container_width`` is ``True``, Streamlit sets
the width of the figure to match the width of the parent container.
.. deprecated::
``use_container_width`` is deprecated and will be removed in a
future release. For ``use_container_width=True``, use
``width="stretch"``. For ``use_container_width=False``, use
``width="content"``.
width : "content", "stretch", or int
The width of the chart element. This can be one of the following:
- ``"content"`` (default): The width of the element matches the
width of its content, but doesn't exceed the width of the parent
container.
- ``"stretch"``: The width of the element matches the width of the
parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
height : "content", "stretch", or int
The height of the chart element. This can be one of the following:
- ``"content"`` (default): The height of the element matches the
height of its content.
- ``"stretch"``: The height of the element matches the height of
its content or the height of the parent container, whichever is
larger. If the element is not in a parent container, the height
of the element matches the height of its content.
- An integer specifying the height in pixels: The element has a
fixed height. If the content is larger than the specified
height, scrolling is enabled.
Example
-------
>>> import streamlit as st
>>> import graphviz
>>>
>>> # Create a graphlib graph object
>>> graph = graphviz.Digraph()
>>> graph.edge("run", "intr")
>>> graph.edge("intr", "runbl")
>>> graph.edge("runbl", "run")
>>> graph.edge("run", "kernel")
>>> graph.edge("kernel", "zombie")
>>> graph.edge("kernel", "sleep")
>>> graph.edge("kernel", "runmem")
>>> graph.edge("sleep", "swap")
>>> graph.edge("swap", "runswap")
>>> graph.edge("runswap", "new")
>>> graph.edge("runswap", "runmem")
>>> graph.edge("new", "runmem")
>>> graph.edge("sleep", "runmem")
>>>
>>> st.graphviz_chart(graph)
Or you can render the chart from the graph using GraphViz's Dot
language:
>>> st.graphviz_chart('''
digraph {
run -> intr
intr -> runbl
runbl -> run
run -> kernel
kernel -> zombie
kernel -> sleep
kernel -> runmem
sleep -> swap
swap -> runswap
runswap -> new
runswap -> runmem
new -> runmem
sleep -> runmem
}
''')
.. output::
https://doc-graphviz-chart.streamlit.app/
height: 600px
"""
if use_container_width is not None:
show_deprecation_warning(
make_deprecated_name_warning(
"use_container_width",
"width",
"2025-12-31",
"For `use_container_width=True`, use `width='stretch'`. "
"For `use_container_width=False`, use `width='content'`.",
include_st_prefix=False,
),
show_in_browser=False,
)
width = "stretch" if use_container_width else "content"
# Generate element ID from delta path
delta_path = self.dg._get_delta_path_str()
element_id = calc_md5(delta_path.encode())
graphviz_chart_proto = GraphVizChartProto()
marshall(graphviz_chart_proto, figure_or_dot, element_id)
# Validate and set layout configuration
validate_width(width, allow_content=True)
validate_height(height, allow_content=True)
layout_config = LayoutConfig(width=width, height=height)
return self.dg._enqueue(
"graphviz_chart", graphviz_chart_proto, layout_config=layout_config
)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
def marshall(
proto: GraphVizChartProto,
figure_or_dot: FigureOrDot,
element_id: str,
) -> None:
"""Construct a GraphViz chart object.
See DeltaGenerator.graphviz_chart for docs.
"""
if type_util.is_graphviz_chart(figure_or_dot):
dot = figure_or_dot.source
engine = figure_or_dot.engine
elif isinstance(figure_or_dot, str):
dot = figure_or_dot
engine = "dot"
else:
raise StreamlitAPIException(
f"Unhandled type for graphviz chart: {type(figure_or_dot)}"
)
proto.spec = dot
proto.engine = engine
proto.element_id = element_id
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/bokeh_chart.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
"""A Python wrapper around Bokeh."""
from __future__ import annotations
from typing import TYPE_CHECKING, cast
from streamlit.deprecation_util import (
show_deprecation_warning,
)
from streamlit.runtime.metrics_util import gather_metrics
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
class BokehMixin:
@gather_metrics("bokeh_chart")
def bokeh_chart(
self,
figure: object, # noqa: ARG002
use_container_width: bool = True, # noqa: ARG002
) -> DeltaGenerator:
"""Display an interactive Bokeh chart.
Bokeh is a charting library for Python. You can find
more about Bokeh at https://bokeh.pydata.org.
.. Important::
This command has been deprecated and removed. Please use our custom
component, |streamlit-bokeh|_, instead. Calling st.bokeh_chart will
do nothing.
.. |streamlit-bokeh| replace:: ``streamlit-bokeh``
.. _streamlit-bokeh: https://github.com/streamlit/streamlit-bokeh
Parameters
----------
figure : bokeh.plotting.figure.Figure
A Bokeh figure to plot.
use_container_width : bool
Whether to override the figure's native width with the width of
the parent container. If ``use_container_width`` is ``True`` (default),
Streamlit sets the width of the figure to match the width of the parent
container. If ``use_container_width`` is ``False``, Streamlit sets the
width of the chart to fit its contents according to the plotting library,
up to the width of the parent container.
"""
show_deprecation_warning(
"st.bokeh_chart has been deprecated and removed. "
"Please use our custom component, "
"[streamlit-bokeh](https://github.com/streamlit/streamlit-bokeh), "
"instead. Calling st.bokeh_chart will do nothing."
)
return self.dg
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/metric.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from dataclasses import dataclass
from textwrap import dedent
from typing import TYPE_CHECKING, Any, Final, Literal, TypeAlias, cast
from streamlit.dataframe_util import OptionSequence, convert_anything_to_list
from streamlit.elements.lib.layout_utils import (
Height,
LayoutConfig,
Width,
validate_height,
validate_width,
)
from streamlit.elements.lib.policies import maybe_raise_label_warnings
from streamlit.elements.lib.utils import (
LabelVisibility,
get_label_visibility_proto_value,
)
from streamlit.errors import StreamlitAPIException, StreamlitValueError
from streamlit.proto.Metric_pb2 import Metric as MetricProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.string_util import AnyNumber, clean_text, from_number
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
from streamlit.elements.lib.column_types import NumberFormat
Value: TypeAlias = AnyNumber | str | None
Delta: TypeAlias = AnyNumber | str | None
DeltaColor: TypeAlias = Literal[
"normal",
"inverse",
"off",
"red",
"orange",
"yellow",
"green",
"blue",
"violet",
"gray",
"grey",
"primary",
]
DeltaArrow: TypeAlias = Literal["auto", "up", "down", "off"]
# Mapping from delta_color string values to proto enum values
_DELTA_COLOR_TO_PROTO: Final[dict[str, MetricProto.MetricColor.ValueType]] = {
"red": MetricProto.MetricColor.RED,
"orange": MetricProto.MetricColor.ORANGE,
"yellow": MetricProto.MetricColor.YELLOW,
"green": MetricProto.MetricColor.GREEN,
"blue": MetricProto.MetricColor.BLUE,
"violet": MetricProto.MetricColor.VIOLET,
"gray": MetricProto.MetricColor.GRAY,
"grey": MetricProto.MetricColor.GRAY,
"primary": MetricProto.MetricColor.PRIMARY,
}
# Valid delta_color values for validation
_VALID_DELTA_COLORS: Final[set[str]] = {
"normal",
"inverse",
"off",
*_DELTA_COLOR_TO_PROTO.keys(),
}
@dataclass(frozen=True)
class MetricColorAndDirection:
color: MetricProto.MetricColor.ValueType
direction: MetricProto.MetricDirection.ValueType
class MetricMixin:
@gather_metrics("metric")
def metric(
self,
label: str,
value: Value,
delta: Delta = None,
delta_color: DeltaColor = "normal",
*,
help: str | None = None,
label_visibility: LabelVisibility = "visible",
border: bool = False,
width: Width = "stretch",
height: Height = "content",
chart_data: OptionSequence[Any] | None = None,
chart_type: Literal["line", "bar", "area"] = "line",
delta_arrow: DeltaArrow = "auto",
format: str | NumberFormat | None = None,
) -> DeltaGenerator:
r"""Display a metric in big bold font, with an optional indicator of how the metric changed.
Tip: If you want to display a large number, it may be a good idea to
shorten it using packages like `millify <https://github.com/azaitsev/millify>`_
or `numerize <https://github.com/davidsa03/numerize>`_. E.g. ``1234`` can be
displayed as ``1.2k`` using ``st.metric("Short number", millify(1234))``.
Parameters
----------
label : str
The header or title for the metric. The label can optionally
contain GitHub-flavored Markdown of the following types: Bold, Italics,
Strikethroughs, Inline Code, Links, and Images. Images display like
icons, with a max height equal to the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
value : int, float, decimal.Decimal, str, or None
Value of the metric. ``None`` is rendered as a long dash.
The value can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
delta : int, float, decimal.Decimal, str, or None
Indicator of how the metric changed, rendered with an arrow below
the metric. If delta is negative (int/float) or starts with a minus
sign (str), the arrow points down and the text is red; else the
arrow points up and the text is green. If None (default), no delta
indicator is shown.
The delta can optionally contain GitHub-flavored Markdown
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
delta_color : str
The color of the delta indicator. This can be one of the following:
- ``"normal"`` (default): The delta indicator is green when
positive and red when negative.
- ``"inverse"``: The delta indicator is red when positive and
green when negative. This is useful when a negative change is
considered good, e.g. if cost decreased.
- ``"off"``: The delta indicator is shown in gray regardless of
its value.
- A named color from the basic palette: ``"red"``, ``"orange"``,
``"yellow"``, ``"green"``, ``"blue"``, ``"violet"``,
``"gray"``/``"grey"``, or ``"primary"``. The delta indicator
and chart uses that color regardless of its value.
help : str or None
A tooltip that gets displayed next to the metric label. Streamlit
only displays the tooltip when ``label_visibility="visible"``. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
label_visibility : "visible", "hidden", or "collapsed"
The visibility of the label. The default is ``"visible"``. If this
is ``"hidden"``, Streamlit displays an empty spacer instead of the
label, which can help keep the widget aligned with other widgets.
If this is ``"collapsed"``, Streamlit displays no label or spacer.
border : bool
Whether to show a border around the metric container. If this is
``False`` (default), no border is shown. If this is ``True``, a
border is shown.
height : "content", "stretch", or int
The height of the metric element. This can be one of the following:
- ``"content"`` (default): The height of the element matches the
height of its content.
- ``"stretch"``: The height of the element matches the height of
its content or the height of the parent container, whichever is
larger. If the element is not in a parent container, the height
of the element matches the height of its content.
- An integer specifying the height in pixels: The element has a
fixed height. If the content is larger than the specified
height, scrolling is enabled.
width : "stretch", "content", or int
The width of the metric element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- ``"content"``: The width of the element matches the width of its
content, but doesn't exceed the width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
chart_data : Iterable or None
A sequence of numeric values to display as a sparkline chart. If
this is ``None`` (default), no chart is displayed. The sequence can
be anything supported by ``st.dataframe``, including a ``list`` or
``set``. If the sequence is dataframe-like, the first column will
be used. Each value will be cast to ``float`` internally by
default.
chart_type : "line", "bar", or "area"
The type of sparkline chart to display. This can be one of the
following:
- ``"line"`` (default): A simple sparkline.
- ``"area"``: A sparkline with area shading.
- ``"bar"``: A bar chart.
delta_arrow : "auto", "up", "down", or "off"
Controls the direction of the delta indicator arrow. This can be
one of the following strings:
- ``"auto"`` (default): The arrow direction follows the sign of
``delta``.
- ``"up"`` or ``"down"``: The arrow is forced to point in the
specified direction.
- ``"off"``: No arrow is shown, but the delta value remains
visible.
format : str or None
A format string controlling how numbers are displayed for ``value``
and ``delta``. The format is only applied if the value or delta is
numeric (int, float, or decimal.Decimal). If the value or delta is
a string with non-numeric characters, the format is ignored.
This can be one of the following values:
- ``None`` (default): No formatting is applied.
- ``"plain"``: Show the full number without any formatting (e.g. "1234.567").
- ``"localized"``: Show the number in the default locale format (e.g. "1,234.567").
- ``"percent"``: Show the number as a percentage (e.g. "123456.70%").
- ``"dollar"``: Show the number as a dollar amount (e.g. "$1,234.57").
- ``"euro"``: Show the number as a euro amount (e.g. "€1,234.57").
- ``"yen"``: Show the number as a yen amount (e.g. "¥1,235").
- ``"accounting"``: Show the number in an accounting format (e.g. "1,234.00").
- ``"bytes"``: Show the number in a byte format (e.g. "1.2KB").
- ``"compact"``: Show the number in a compact format (e.g. "1.2K").
- ``"scientific"``: Show the number in scientific notation (e.g. "1.235E3").
- ``"engineering"``: Show the number in engineering notation (e.g. "1.235E3").
- printf-style format string: Format the number with a printf
specifier, like ``"%d"`` to show a signed integer (e.g. "1234") or
``"%.2f"`` to show a float with 2 decimal places.
Examples
--------
**Example 1: Show a metric**
>>> import streamlit as st
>>>
>>> st.metric(label="Temperature", value="70 °F", delta="1.2 °F")
.. output::
https://doc-metric-example1.streamlit.app/
height: 210px
**Example 2: Create a row of metrics**
``st.metric`` looks especially nice in combination with ``st.columns``.
>>> import streamlit as st
>>>
>>> col1, col2, col3 = st.columns(3)
>>> col1.metric("Temperature", "70 °F", "1.2 °F")
>>> col2.metric("Wind", "9 mph", "-8%")
>>> col3.metric("Humidity", "86%", "4%")
.. output::
https://doc-metric-example2.streamlit.app/
height: 210px
**Example 3: Modify the delta indicator**
The delta indicator color can also be inverted or turned off.
>>> import streamlit as st
>>>
>>> st.metric(
... label="Gas price", value=4, delta=-0.5, delta_color="inverse"
... )
>>>
>>> st.metric(
... label="Active developers",
... value=123,
... delta=123,
... delta_color="off",
... )
.. output::
https://doc-metric-example3.streamlit.app/
height: 320px
**Example 4: Create a grid of metric cards**
Add borders to your metrics to create a dashboard look.
>>> import streamlit as st
>>>
>>> a, b = st.columns(2)
>>> c, d = st.columns(2)
>>>
>>> a.metric("Temperature", "30°F", "-9°F", border=True)
>>> b.metric("Wind", "4 mph", "2 mph", border=True)
>>>
>>> c.metric("Humidity", "77%", "5%", border=True)
>>> d.metric("Pressure", "30.34 inHg", "-2 inHg", border=True)
.. output::
https://doc-metric-example4.streamlit.app/
height: 350px
**Example 5: Show sparklines**
To show trends over time, add sparklines.
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> changes = list(rng(4).standard_normal(20))
>>> data = [sum(changes[:i]) for i in range(20)]
>>> delta = round(data[-1], 2)
>>>
>>> row = st.container(horizontal=True)
>>> with row:
>>> st.metric(
... "Line", 10, delta, chart_data=data, chart_type="line", border=True
... )
>>> st.metric(
... "Area", 10, delta, chart_data=data, chart_type="area", border=True
... )
>>> st.metric(
... "Bar", 10, delta, chart_data=data, chart_type="bar", border=True
... )
.. output::
https://doc-metric-example5.streamlit.app/
height: 300px
"""
maybe_raise_label_warnings(label, label_visibility)
metric_proto = MetricProto()
metric_proto.body = _parse_value(value)
metric_proto.label = _parse_label(label)
metric_proto.delta = _parse_delta(delta)
metric_proto.show_border = border
if help is not None:
metric_proto.help = dedent(help)
color_and_direction = _determine_delta_color_and_direction(
cast("DeltaColor", clean_text(delta_color)), delta
)
metric_proto.color = color_and_direction.color
metric_proto.direction = color_and_direction.direction
parsed_delta_arrow = _parse_delta_arrow(
cast("DeltaArrow", clean_text(delta_arrow))
)
if parsed_delta_arrow != "auto":
if parsed_delta_arrow == "off":
metric_proto.direction = MetricProto.MetricDirection.NONE
elif parsed_delta_arrow == "up":
metric_proto.direction = MetricProto.MetricDirection.UP
elif parsed_delta_arrow == "down":
metric_proto.direction = MetricProto.MetricDirection.DOWN
metric_proto.label_visibility.value = get_label_visibility_proto_value(
label_visibility
)
if chart_data is not None:
prepared_data: list[float] = []
for val in convert_anything_to_list(chart_data):
try:
prepared_data.append(float(val))
except Exception as ex: # noqa: PERF203
raise StreamlitAPIException(
"Only numeric values are supported for chart data sequence. The "
f"value '{val}' is of type {type(val)} and "
"cannot be converted to float."
) from ex
if len(prepared_data) > 0:
metric_proto.chart_data.extend(prepared_data)
metric_proto.chart_type = _parse_chart_type(chart_type)
if format is not None:
metric_proto.format = format
validate_height(height, allow_content=True)
validate_width(width, allow_content=True)
layout_config = LayoutConfig(width=width, height=height)
return self.dg._enqueue("metric", metric_proto, layout_config=layout_config)
@property
def dg(self) -> DeltaGenerator:
return cast("DeltaGenerator", self)
def _parse_chart_type(
chart_type: Literal["line", "bar", "area"],
) -> MetricProto.ChartType.ValueType:
if chart_type == "bar":
return MetricProto.ChartType.BAR
if chart_type == "area":
return MetricProto.ChartType.AREA
# Use line as default chart:
return MetricProto.ChartType.LINE
def _parse_delta_arrow(delta_arrow: DeltaArrow) -> DeltaArrow:
if delta_arrow not in {"auto", "up", "down", "off"}:
raise StreamlitValueError("delta_arrow", ["auto", "up", "down", "off"])
return delta_arrow
def _parse_label(label: str) -> str:
if not isinstance(label, str):
raise TypeError(
f"'{label}' is of type {type(label)}, which is not an accepted type."
" label only accepts: str. Please convert the label to an accepted type."
)
return label
def _parse_value(value: Value) -> str:
if value is None:
return "—"
if isinstance(value, str):
return value
return from_number(value)
def _parse_delta(delta: Delta) -> str:
if delta is None or delta == "":
return ""
if isinstance(delta, str):
return dedent(delta)
return from_number(delta)
def _determine_delta_color_and_direction(
delta_color: DeltaColor,
delta: Delta,
) -> MetricColorAndDirection:
if delta_color not in _VALID_DELTA_COLORS:
raise StreamlitAPIException(
f"'{delta_color}' is not an accepted value. delta_color only accepts: "
"'normal', 'inverse', 'off', or a color name ('red', 'orange', 'yellow', "
"'green', 'blue', 'violet', 'gray'/'grey', 'primary')"
)
if delta is None or delta == "":
return MetricColorAndDirection(
color=MetricProto.MetricColor.GRAY,
direction=MetricProto.MetricDirection.NONE,
)
# Determine direction based on delta sign
cd_direction = (
MetricProto.MetricDirection.DOWN
if _is_negative_delta(delta)
else MetricProto.MetricDirection.UP
)
# Handle explicit color names
if delta_color in _DELTA_COLOR_TO_PROTO:
return MetricColorAndDirection(
color=_DELTA_COLOR_TO_PROTO[delta_color],
direction=cd_direction,
)
# Handle "normal", "inverse", "off" modes
is_negative = cd_direction == MetricProto.MetricDirection.DOWN
if delta_color == "normal":
cd_color = (
MetricProto.MetricColor.RED
if is_negative
else MetricProto.MetricColor.GREEN
)
elif delta_color == "inverse":
cd_color = (
MetricProto.MetricColor.GREEN
if is_negative
else MetricProto.MetricColor.RED
)
else: # "off"
cd_color = MetricProto.MetricColor.GRAY
return MetricColorAndDirection(
color=cd_color,
direction=cd_direction,
)
def _is_negative_delta(delta: Delta) -> bool:
return dedent(str(delta)).startswith("-")
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/iframe.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from typing import TYPE_CHECKING, cast
from streamlit.elements.lib.layout_utils import LayoutConfig
from streamlit.errors import StreamlitAPIException
from streamlit.proto.IFrame_pb2 import IFrame as IFrameProto
from streamlit.runtime.metrics_util import gather_metrics
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
class IframeMixin:
@gather_metrics("_iframe")
def _iframe(
self,
src: str,
width: int | None = None,
height: int | None = None,
scrolling: bool = False,
*,
tab_index: int | None = None,
) -> DeltaGenerator:
"""Load a remote URL in an iframe.
To use this function, import it from the ``streamlit.components.v1``
module.
.. warning::
Using ``st.components.v1.iframe`` directly (instead of importing
its module) is deprecated and will be disallowed in a later version.
Parameters
----------
src : str
The URL of the page to embed.
width : int
The width of the iframe in CSS pixels. By default, this is the
app's default element width.
height : int
The height of the frame in CSS pixels. By default, this is ``150``.
scrolling : bool
Whether to allow scrolling in the iframe. If this ``False``
(default), Streamlit crops any content larger than the iframe and
does not show a scrollbar. If this is ``True``, Streamlit shows a
scrollbar when the content is larger than the iframe.
tab_index : int or None
Specifies how and if the iframe is sequentially focusable.
Users typically use the ``Tab`` key for sequential focus
navigation.
This can be one of the following values:
- ``None`` (default): Uses the browser's default behavior.
- ``-1``: Removes the iframe from sequential navigation, but still
allows it to be focused programmatically.
- ``0``: Includes the iframe in sequential navigation in the order
it appears in the document but after all elements with a positive
``tab_index``.
- Positive integer: Includes the iframe in sequential navigation.
Elements are navigated in ascending order of their positive
``tab_index``.
For more information, see the `tabindex
<https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex>`_
documentation on MDN.
Example
-------
>>> import streamlit.components.v1 as components
>>>
>>> components.iframe("https://example.com", height=500)
"""
iframe_proto = IFrameProto()
marshall(
iframe_proto,
src=src,
scrolling=scrolling,
tab_index=tab_index,
)
layout_config = LayoutConfig(
width=width if width is not None else "stretch",
height=height if height is not None else 150,
)
return self.dg._enqueue("iframe", iframe_proto, layout_config=layout_config)
@gather_metrics("_html")
def _html(
self,
html: str,
width: int | None = None,
height: int | None = None,
scrolling: bool = False,
*,
tab_index: int | None = None,
) -> DeltaGenerator:
"""Display an HTML string in an iframe.
To use this function, import it from the ``streamlit.components.v1``
module.
If you want to insert HTML text into your app without an iframe, try
``st.html`` instead.
.. warning::
Using ``st.components.v1.html`` directly (instead of importing
its module) is deprecated and will be disallowed in a later version.
Parameters
----------
html : str
The HTML string to embed in the iframe.
width : int
The width of the iframe in CSS pixels. By default, this is the
app's default element width.
height : int
The height of the frame in CSS pixels. By default, this is ``150``.
scrolling : bool
Whether to allow scrolling in the iframe. If this ``False``
(default), Streamlit crops any content larger than the iframe and
does not show a scrollbar. If this is ``True``, Streamlit shows a
scrollbar when the content is larger than the iframe.
tab_index : int or None
Specifies how and if the iframe is sequentially focusable.
Users typically use the ``Tab`` key for sequential focus
navigation.
This can be one of the following values:
- ``None`` (default): Uses the browser's default behavior.
- ``-1``: Removes the iframe from sequential navigation, but still
allows it to be focused programmatically.
- ``0``: Includes the iframe in sequential navigation in the order
it appears in the document but after all elements with a positive
``tab_index``.
- Positive integer: Includes the iframe in sequential navigation.
Elements are navigated in ascending order of their positive
``tab_index``.
For more information, see the `tabindex
<https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex>`_
documentation on MDN.
Example
-------
>>> import streamlit.components.v1 as components
>>>
>>> components.html(
>>> "<p><span style='text-decoration: line-through double red;'>Oops</span>!</p>"
>>> )
"""
iframe_proto = IFrameProto()
marshall(
iframe_proto,
srcdoc=html,
scrolling=scrolling,
tab_index=tab_index,
)
layout_config = LayoutConfig(
width=width if width is not None else "stretch",
height=height if height is not None else 150,
)
return self.dg._enqueue("iframe", iframe_proto, layout_config=layout_config)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
def marshall(
proto: IFrameProto,
src: str | None = None,
srcdoc: str | None = None,
scrolling: bool = False,
tab_index: int | None = None,
) -> None:
"""Marshalls data into an IFrame proto.
These parameters correspond directly to <iframe> attributes, which are
described in more detail at
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe.
Parameters
----------
proto : IFrame protobuf
The protobuf object to marshall data into.
src : str
The URL of the page to embed.
srcdoc : str
Inline HTML to embed. Overrides src.
scrolling : bool
If true, show a scrollbar when the content is larger than the iframe.
Otherwise, never show a scrollbar.
tab_index : int, optional
Specifies the tab order of the iframe.
"""
if src is not None:
proto.src = src
if srcdoc is not None:
proto.srcdoc = srcdoc
proto.scrolling = scrolling
if tab_index is not None:
# Validate tab_index according to web specifications
if not (
isinstance(tab_index, int)
and not isinstance(tab_index, bool)
and tab_index >= -1
):
raise StreamlitAPIException(
"tab_index must be None, -1, or a non-negative integer."
)
proto.tab_index = tab_index
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/markdown.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from typing import TYPE_CHECKING, Final, Literal, cast
from streamlit.elements.lib.layout_utils import (
LayoutConfig,
TextAlignment,
Width,
WidthWithoutContent,
validate_width,
)
from streamlit.proto.Markdown_pb2 import Markdown as MarkdownProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.string_util import clean_text, validate_icon_or_emoji
from streamlit.type_util import SupportsStr, is_sympy_expression
if TYPE_CHECKING:
import sympy
from streamlit.delta_generator import DeltaGenerator
MARKDOWN_HORIZONTAL_RULE_EXPRESSION: Final = "---"
class MarkdownMixin:
@gather_metrics("markdown")
def markdown(
self,
body: SupportsStr,
unsafe_allow_html: bool = False,
*, # keyword-only arguments:
help: str | None = None,
width: Width = "stretch",
text_alignment: TextAlignment = "left",
) -> DeltaGenerator:
r"""Display string formatted as Markdown.
Parameters
----------
body : any
The text to display as GitHub-flavored Markdown. Syntax
information can be found at: https://github.github.com/gfm.
If anything other than a string is passed, it will be converted
into a string behind the scenes using ``str(body)``.
This also supports:
- Emoji shortcodes, such as ``:+1:`` and ``:sunglasses:``.
For a list of all supported codes,
see https://share.streamlit.io/streamlit/emoji-shortcodes.
- Streamlit logo shortcode. Use ``:streamlit:`` to add a little
Streamlit flair to your text.
- A limited set of typographical symbols. ``"<- -> <-> -- >= <= ~="``
becomes "← → ↔ — ≥ ≤ ≈" when parsed as Markdown.
- Google Material Symbols (rounded style), using the syntax
``:material/icon_name:``, where "icon_name" is the name of the
icon in snake case. For a complete list of icons, see Google's
`Material Symbols <https://fonts.google.com/icons?icon.set=Material+Symbols&icon.style=Rounded>`_
font library.
- LaTeX expressions, by wrapping them in "$" or "$$" (the "$$"
must be on their own lines). Supported LaTeX functions are listed
at https://katex.org/docs/supported.html.
- Colored text and background colors for text, using the syntax
``:color[text to be colored]`` and ``:color-background[text to be colored]``,
respectively. ``color`` must be replaced with any of the following
supported colors: red, orange, yellow, green, blue, violet, gray/grey,
rainbow, or primary. For example, you can use
``:orange[your text here]`` or ``:blue-background[your text here]``.
If you use "primary" for color, Streamlit will use the default
primary accent color unless you set the ``theme.primaryColor``
configuration option.
- Colored badges, using the syntax ``:color-badge[text in the badge]``.
``color`` must be replaced with any of the following supported
colors: red, orange, yellow, green, blue, violet, gray/grey, or primary.
For example, you can use ``:orange-badge[your text here]`` or
``:blue-badge[your text here]``.
- Small text, using the syntax ``:small[text to show small]``.
unsafe_allow_html : bool
Whether to render HTML within ``body``. If this is ``False``
(default), any HTML tags found in ``body`` will be escaped and
therefore treated as raw text. If this is ``True``, any HTML
expressions within ``body`` will be rendered.
Adding custom HTML to your app impacts safety, styling, and
maintainability.
.. note::
If you only want to insert HTML or CSS without Markdown text,
we recommend using ``st.html`` instead.
help : str or None
A tooltip that gets displayed next to the Markdown. If this is
``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
width : "stretch", "content", or int
The width of the Markdown element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- ``"content"``: The width of the element matches the width of its
content, but doesn't exceed the width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
text_alignment : "left", "center", "right", or "justify"
The horizontal alignment of the text within the element. This can
be one of the following:
- ``"left"`` (default): Text is aligned to the left edge.
- ``"center"``: Text is centered.
- ``"right"``: Text is aligned to the right edge.
- ``"justify"``: Text is justified (stretched to fill the available
width with the last line left-aligned).
.. note::
For text alignment to have a visible effect, the element's
width must be wider than its content. If you use
``width="content"`` with short text, the alignment may not be
noticeable.
Examples
--------
>>> import streamlit as st
>>>
>>> st.markdown("*Streamlit* is **really** ***cool***.")
>>> st.markdown('''
... :red[Streamlit] :orange[can] :green[write] :blue[text] :violet[in]
... :gray[pretty] :rainbow[colors] and :blue-background[highlight] text.''')
>>> st.markdown("Here's a bouquet —\
... :tulip::cherry_blossom::rose::hibiscus::sunflower::blossom:")
>>>
>>> multi = '''If you end a line with two spaces,
... a soft return is used for the next line.
...
... Two (or more) newline characters in a row will result in a hard return.
... '''
>>> st.markdown(multi)
.. output::
https://doc-markdown.streamlit.app/
height: 350px
"""
markdown_proto = MarkdownProto()
markdown_proto.body = clean_text(body)
markdown_proto.allow_html = unsafe_allow_html
markdown_proto.element_type = MarkdownProto.Type.NATIVE
if help:
markdown_proto.help = help
validate_width(width, allow_content=True)
layout_config = LayoutConfig(width=width, text_alignment=text_alignment)
return self.dg._enqueue("markdown", markdown_proto, layout_config=layout_config)
@gather_metrics("caption")
def caption(
self,
body: SupportsStr,
unsafe_allow_html: bool = False,
*, # keyword-only arguments:
help: str | None = None,
width: Width = "stretch",
text_alignment: TextAlignment = "left",
) -> DeltaGenerator:
"""Display text in small font.
This should be used for captions, asides, footnotes, sidenotes, and
other explanatory text.
Parameters
----------
body : str
The text to display as GitHub-flavored Markdown. Syntax
information can be found at: https://github.github.com/gfm.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
unsafe_allow_html : bool
Whether to render HTML within ``body``. If this is ``False``
(default), any HTML tags found in ``body`` will be escaped and
therefore treated as raw text. If this is ``True``, any HTML
expressions within ``body`` will be rendered.
Adding custom HTML to your app impacts safety, styling, and
maintainability.
.. note::
If you only want to insert HTML or CSS without Markdown text,
we recommend using ``st.html`` instead.
help : str or None
A tooltip that gets displayed next to the caption. If this is
``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
width : "stretch", "content", or int
The width of the caption element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- ``"content"``: The width of the element matches the width of its
content, but doesn't exceed the width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
text_alignment : "left", "center", "right", or "justify"
The horizontal alignment of the text within the element. This can
be one of the following:
- ``"left"`` (default): Text is aligned to the left edge.
- ``"center"``: Text is centered.
- ``"right"``: Text is aligned to the right edge.
- ``"justify"``: Text is justified (stretched to fill the available
width with the last line left-aligned).
.. note::
For text alignment to have a visible effect, the element's
width must be wider than its content. If you use
``width="content"`` with short text, the alignment may not be
noticeable.
Examples
--------
>>> import streamlit as st
>>>
>>> st.caption("This is a string that explains something above.")
>>> st.caption("A caption with _italics_ :blue[colors] and emojis :sunglasses:")
"""
caption_proto = MarkdownProto()
caption_proto.body = clean_text(body)
caption_proto.allow_html = unsafe_allow_html
caption_proto.is_caption = True
caption_proto.element_type = MarkdownProto.Type.CAPTION
if help:
caption_proto.help = help
validate_width(width, allow_content=True)
layout_config = LayoutConfig(width=width, text_alignment=text_alignment)
return self.dg._enqueue("markdown", caption_proto, layout_config=layout_config)
@gather_metrics("latex")
def latex(
self,
body: SupportsStr | sympy.Expr,
*, # keyword-only arguments:
help: str | None = None,
width: Width = "stretch",
) -> DeltaGenerator:
# This docstring needs to be "raw" because of the backslashes in the
# example below.
r"""Display mathematical expressions formatted as LaTeX.
Supported LaTeX functions are listed at
https://katex.org/docs/supported.html.
Parameters
----------
body : str or SymPy expression
The string or SymPy expression to display as LaTeX. If str, it's
a good idea to use raw Python strings since LaTeX uses backslashes
a lot.
help : str or None
A tooltip that gets displayed next to the LaTeX expression. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
width : "stretch", "content", or int
The width of the LaTeX element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- ``"content"``: The width of the element matches the width of its
content, but doesn't exceed the width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
Example
-------
>>> import streamlit as st
>>>
>>> st.latex(r'''
... a + ar + a r^2 + a r^3 + \cdots + a r^{n-1} =
... \sum_{k=0}^{n-1} ar^k =
... a \left(\frac{1-r^{n}}{1-r}\right)
... ''')
"""
if is_sympy_expression(body):
import sympy
body = sympy.latex(body)
latex_proto = MarkdownProto()
latex_proto.body = f"$$\n{clean_text(body)}\n$$"
latex_proto.element_type = MarkdownProto.Type.LATEX
if help:
latex_proto.help = help
validate_width(width, allow_content=True)
layout_config = LayoutConfig(width=width)
return self.dg._enqueue("markdown", latex_proto, layout_config=layout_config)
@gather_metrics("divider")
def divider(self, *, width: WidthWithoutContent = "stretch") -> DeltaGenerator:
"""Display a horizontal rule.
.. note::
You can achieve the same effect with st.write("---") or
even just "---" in your script (via magic).
Parameters
----------
width : "stretch" or int
The width of the divider element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
Example
-------
>>> import streamlit as st
>>>
>>> st.divider()
"""
divider_proto = MarkdownProto()
divider_proto.body = MARKDOWN_HORIZONTAL_RULE_EXPRESSION
divider_proto.element_type = MarkdownProto.Type.DIVIDER
validate_width(width, allow_content=False)
layout_config = LayoutConfig(width=width)
return self.dg._enqueue("markdown", divider_proto, layout_config=layout_config)
@gather_metrics("badge")
def badge(
self,
label: str,
*, # keyword-only arguments:
icon: str | None = None,
color: Literal[
"red",
"orange",
"yellow",
"blue",
"green",
"violet",
"gray",
"grey",
"primary",
] = "blue",
width: Width = "content",
help: str | None = None,
) -> DeltaGenerator:
"""Display a colored badge with an icon and label.
This is a thin wrapper around the color-badge Markdown directive.
The following are equivalent:
- ``st.markdown(":blue-badge[Home]")``
- ``st.badge("Home", color="blue")``
.. note::
You can insert badges everywhere Streamlit supports Markdown by
using the color-badge Markdown directive. See ``st.markdown`` for
more information.
Parameters
----------
label : str
The label to display in the badge. The label can optionally contain
GitHub-flavored Markdown of the following types: Bold, Italics,
Strikethroughs, Inline Code.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives. Because this command escapes square
brackets (``[ ]``) in this parameter, any directive requiring
square brackets is not supported.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
icon : str or None
An optional emoji or icon to display next to the badge label. If
``icon`` is ``None`` (default), no icon is displayed. If ``icon``
is a string, the following options are valid:
- A single-character emoji. For example, you can set ``icon="🚨"``
or ``icon="🔥"``. Emoji short codes are not supported.
- An icon from the Material Symbols library (rounded style) in the
format ``":material/icon_name:"`` where "icon_name" is the name
of the icon in snake case.
For example, ``icon=":material/thumb_up:"`` will display the
Thumb Up icon. Find additional icons in the `Material Symbols \
<https://fonts.google.com/icons?icon.set=Material+Symbols&icon.style=Rounded>`_
font library.
color : str
The color to use for the badge. This defaults to ``"blue"``.
This can be one of the following supported colors: red, orange,
yellow, blue, green, violet, gray/grey, or primary. If you use
``"primary"``, Streamlit will use the default primary accent color
unless you set the ``theme.primaryColor`` configuration option.
width : "content", "stretch", or int
The width of the badge element. This can be one of the following:
- ``"content"`` (default): The width of the element matches the
width of its content, but doesn't exceed the width of the parent
container.
- ``"stretch"``: The width of the element matches the width of the
parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
help : str or None
A tooltip to display when hovering over the badge. If this is
``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
Examples
--------
Create standalone badges with ``st.badge`` (with or without icons). If
you want to have multiple, side-by-side badges, you can use the
Markdown directive in ``st.markdown``.
>>> import streamlit as st
>>>
>>> st.badge("New")
>>> st.badge("Success", icon=":material/check:", color="green")
>>>
>>> st.markdown(
>>> ":violet-badge[:material/star: Favorite] :orange-badge[⚠️ Needs review] :gray-badge[Deprecated]"
>>> )
.. output::
https://doc-badge.streamlit.app/
height: 220px
"""
icon_str = validate_icon_or_emoji(icon) + " " if icon is not None else ""
# Escape [ and ] characters in the label to prevent breaking the directive syntax
escaped_label = label.replace("[", "\\[").replace("]", "\\]")
badge_proto = MarkdownProto()
badge_proto.body = f":{color}-badge[{icon_str}{escaped_label}]"
badge_proto.element_type = MarkdownProto.Type.NATIVE
if help is not None:
badge_proto.help = help
validate_width(width, allow_content=True)
layout_config = LayoutConfig(width=width)
return self.dg._enqueue("markdown", badge_proto, layout_config=layout_config)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/deck_gl_json_chart.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import json
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
Any,
Final,
Literal,
TypeAlias,
TypedDict,
cast,
overload,
)
from streamlit import config
from streamlit.deprecation_util import (
make_deprecated_name_warning,
show_deprecation_warning,
)
from streamlit.elements.lib.form_utils import current_form_id
from streamlit.elements.lib.layout_utils import (
HeightWithoutContent,
LayoutConfig,
WidthWithoutContent,
validate_height,
validate_width,
)
from streamlit.elements.lib.policies import check_widget_policies
from streamlit.elements.lib.utils import Key, compute_and_register_element_id, to_key
from streamlit.errors import StreamlitAPIException
from streamlit.proto.DeckGlJsonChart_pb2 import DeckGlJsonChart as PydeckProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner_utils.script_run_context import get_script_run_ctx
from streamlit.runtime.state import (
WidgetCallback,
register_widget,
)
from streamlit.util import AttributeDictionary
if TYPE_CHECKING:
from collections.abc import Iterable, Mapping
from pydeck import Deck
from streamlit.delta_generator import DeltaGenerator
# Mapping used when no data is passed.
EMPTY_MAP: Final[Mapping[str, Any]] = {
"initialViewState": {"latitude": 0, "longitude": 0, "pitch": 0, "zoom": 1},
}
SelectionMode: TypeAlias = Literal["single-object", "multi-object"]
_SELECTION_MODES: Final[set[SelectionMode]] = {
"single-object",
"multi-object",
}
def parse_selection_mode(
selection_mode: SelectionMode | Iterable[SelectionMode],
) -> set[PydeckProto.SelectionMode.ValueType]:
"""Parse and check the user provided selection modes."""
if isinstance(selection_mode, str):
# Only a single selection mode was passed
selection_mode_set = {selection_mode}
else:
# Multiple selection modes were passed.
# This is not yet supported as a functionality, but the infra is here to
# support it in the future!
# @see DeckGlJsonChart.tsx
raise StreamlitAPIException(
f"Invalid selection mode: {selection_mode}. ",
"Selection mode must be a single value, but got a set instead.",
)
if not selection_mode_set.issubset(_SELECTION_MODES):
raise StreamlitAPIException(
f"Invalid selection mode: {selection_mode}. "
f"Valid options are: {_SELECTION_MODES}"
)
if selection_mode_set.issuperset({"single-object", "multi-object"}):
raise StreamlitAPIException(
"Only one of `single-object` or `multi-object` can be selected as selection mode."
)
parsed_selection_modes = []
for mode in selection_mode_set:
if mode == "single-object":
parsed_selection_modes.append(PydeckProto.SelectionMode.SINGLE_OBJECT)
elif mode == "multi-object":
parsed_selection_modes.append(PydeckProto.SelectionMode.MULTI_OBJECT)
return set(parsed_selection_modes)
class PydeckSelectionState(TypedDict, total=False):
r"""
The schema for the PyDeck chart selection state.
The selection state is stored in a dictionary-like object that supports
both key and attribute notation. Selection states cannot be
programmatically changed or set through Session State.
You must define ``id`` in ``pydeck.Layer`` to ensure statefulness when
using selections with ``st.pydeck_chart``.
Attributes
----------
indices : dict[str, list[int]]
A dictionary of selected objects by layer. Each key in the dictionary
is a layer id, and each value is a list of object indices within that
layer.
objects : dict[str, list[dict[str, Any]]]
A dictionary of object attributes by layer. Each key in the dictionary
is a layer id, and each value is a list of metadata dictionaries for
the selected objects in that layer.
Examples
--------
The following example has multi-object selection enabled. The chart
displays US state capitals by population (2023 US Census estimate). You
can access this `data
<https://github.com/streamlit/docs/blob/main/python/api-examples-source/data/capitals.csv>`_
from GitHub.
>>> import streamlit as st
>>> import pydeck
>>> import pandas as pd
>>>
>>> capitals = pd.read_csv(
... "capitals.csv",
... header=0,
... names=[
... "Capital",
... "State",
... "Abbreviation",
... "Latitude",
... "Longitude",
... "Population",
... ],
... )
>>> capitals["size"] = capitals.Population / 10
>>>
>>> point_layer = pydeck.Layer(
... "ScatterplotLayer",
... data=capitals,
... id="capital-cities",
... get_position=["Longitude", "Latitude"],
... get_color="[255, 75, 75]",
... pickable=True,
... auto_highlight=True,
... get_radius="size",
... )
>>>
>>> view_state = pydeck.ViewState(
... latitude=40, longitude=-117, controller=True, zoom=2.4, pitch=30
... )
>>>
>>> chart = pydeck.Deck(
... point_layer,
... initial_view_state=view_state,
... tooltip={"text": "{Capital}, {Abbreviation}\nPopulation: {Population}"},
... )
>>>
>>> event = st.pydeck_chart(chart, on_select="rerun", selection_mode="multi-object")
>>>
>>> event.selection
.. output::
https://doc-pydeck-event-state-selections.streamlit.app/
height: 700px
This is an example of the selection state when selecting a single object
from a layer with id, ``"captial-cities"``:
>>> {
>>> "indices":{
>>> "capital-cities":[
>>> 2
>>> ]
>>> },
>>> "objects":{
>>> "capital-cities":[
>>> {
>>> "Abbreviation":" AZ"
>>> "Capital":"Phoenix"
>>> "Latitude":33.448457
>>> "Longitude":-112.073844
>>> "Population":1650070
>>> "State":" Arizona"
>>> "size":165007.0
>>> }
>>> ]
>>> }
>>> }
"""
indices: dict[str, list[int]]
objects: dict[str, list[dict[str, Any]]]
class PydeckState(TypedDict, total=False):
"""
The schema for the PyDeck event state.
The event state is stored in a dictionary-like object that supports both
key and attribute notation. Event states cannot be programmatically changed
or set through Session State.
Only selection events are supported at this time.
Attributes
----------
selection : dict
The state of the ``on_select`` event. This attribute returns a
dictionary-like object that supports both key and attribute notation.
The attributes are described by the ``PydeckSelectionState``
dictionary schema.
"""
selection: PydeckSelectionState
@dataclass
class PydeckSelectionSerde:
"""PydeckSelectionSerde is used to serialize and deserialize the Pydeck selection state."""
def deserialize(self, ui_value: str | None) -> PydeckState:
empty_selection_state: PydeckState = {
"selection": {
"indices": {},
"objects": {},
}
}
selection_state = (
empty_selection_state if ui_value is None else json.loads(ui_value)
)
# We have seen some situations where the ui_value was just an empty
# dict, so we want to ensure that it always returns the empty state in
# case this happens.
if "selection" not in selection_state:
selection_state = empty_selection_state
return cast("PydeckState", AttributeDictionary(selection_state))
def serialize(self, selection_state: PydeckState) -> str:
return json.dumps(selection_state, default=str)
class PydeckMixin:
@overload
def pydeck_chart(
self,
pydeck_obj: Deck | None = None,
*,
width: WidthWithoutContent = "stretch",
use_container_width: bool | None = None,
height: HeightWithoutContent = 500,
selection_mode: Literal[
"single-object"
], # Selection mode will only be activated by on_select param; default value here to make it work with mypy
# No default value here to make it work with mypy
on_select: Literal["ignore"],
key: Key | None = None,
) -> DeltaGenerator: ...
@overload
def pydeck_chart(
self,
pydeck_obj: Deck | None = None,
*,
width: WidthWithoutContent = "stretch",
use_container_width: bool | None = None,
height: HeightWithoutContent = 500,
selection_mode: SelectionMode = "single-object",
on_select: Literal["rerun"] | WidgetCallback = "rerun",
key: Key | None = None,
) -> PydeckState: ...
@gather_metrics("pydeck_chart")
def pydeck_chart(
self,
pydeck_obj: Deck | None = None,
*,
width: WidthWithoutContent = "stretch",
use_container_width: bool | None = None,
height: HeightWithoutContent = 500,
selection_mode: SelectionMode = "single-object",
on_select: Literal["rerun", "ignore"] | WidgetCallback = "ignore",
key: Key | None = None,
) -> DeltaGenerator | PydeckState:
"""Draw a chart using the PyDeck library.
This supports 3D maps, point clouds, and more! More info about PyDeck
at https://deckgl.readthedocs.io/en/latest/.
These docs are also quite useful:
- DeckGL docs: https://github.com/uber/deck.gl/tree/master/docs
- DeckGL JSON docs: https://github.com/uber/deck.gl/tree/master/modules/json
When using this command, a service called Carto_ provides the map tiles to render
map content. If you're using advanced PyDeck features you may need to obtain
an API key from Carto first. You can do that as
``pydeck.Deck(api_keys={"carto": YOUR_KEY})`` or by setting the CARTO_API_KEY
environment variable. See `PyDeck's documentation`_ for more information.
Another common provider for map tiles is Mapbox_. If you prefer to use that,
you'll need to create an account at https://mapbox.com and specify your Mapbox
key when creating the ``pydeck.Deck`` object. You can do that as
``pydeck.Deck(api_keys={"mapbox": YOUR_KEY})`` or by setting the MAPBOX_API_KEY
environment variable.
.. _Carto: https://carto.com
.. _Mapbox: https://mapbox.com
.. _PyDeck's documentation: https://deckgl.readthedocs.io/en/latest/deck.html
Carto and Mapbox are third-party products and Streamlit accepts no responsibility
or liability of any kind for Carto or Mapbox, or for any content or information
made available by Carto or Mapbox. The use of Carto or Mapbox is governed by
their respective Terms of Use.
.. note::
Pydeck uses two WebGL contexts per chart, and different browsers
have different limits on the number of WebGL contexts per page.
If you exceed this limit, the oldest contexts will be dropped to
make room for the new ones. To avoid this limitation in most
browsers, don't display more than eight Pydeck charts on a single
page.
Parameters
----------
pydeck_obj : pydeck.Deck or None
Object specifying the PyDeck chart to draw.
width : "stretch" or int
The width of the chart element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
use_container_width : bool or None
Whether to override the chart's native width with the width of
the parent container. This can be one of the following:
- ``None`` (default): Streamlit will use the chart's default behavior.
- ``True``: Streamlit sets the width of the chart to match the
width of the parent container.
- ``False``: Streamlit sets the width of the chart to fit its
contents according to the plotting library, up to the width of
the parent container.
.. deprecated::
``use_container_width`` is deprecated and will be removed in a
future release. For ``use_container_width=True``, use
``width="stretch"``.
height : "stretch" or int
The height of the chart element. This can be one of the following:
- An integer specifying the height in pixels: The element has a
fixed height. If the content is larger than the specified
height, scrolling is enabled. This is ``500`` by default.
- ``"stretch"``: The height of the element matches the height of
its content or the height of the parent container, whichever is
larger. If the element is not in a parent container, the height
of the element matches the height of its content.
on_select : "ignore" or "rerun" or callable
How the figure should respond to user selection events. This controls
whether or not the chart behaves like an input widget.
``on_select`` can be one of the following:
- ``"ignore"`` (default): Streamlit will not react to any selection
events in the chart. The figure will not behave like an
input widget.
- ``"rerun"``: Streamlit will rerun the app when the user selects
data in the chart. In this case, ``st.pydeck_chart`` will return
the selection data as a dictionary.
- A ``callable``: Streamlit will rerun the app and execute the callable
as a callback function before the rest of the app. In this case,
``st.pydeck_chart`` will return the selection data as a
dictionary.
If ``on_select`` is not ``"ignore"``, all layers must have a
declared ``id`` to keep the chart stateful across reruns.
selection_mode : "single-object" or "multi-object"
The selection mode of the chart. This can be one of the following:
- ``"single-object"`` (default): Only one object can be selected at
a time.
- ``"multi-object"``: Multiple objects can be selected at a time.
key : str
An optional string to use for giving this element a stable
identity. If ``key`` is ``None`` (default), this element's identity
will be determined based on the values of the other parameters.
Additionally, if selections are activated and ``key`` is provided,
Streamlit will register the key in Session State to store the
selection state. The selection state is read-only.
Returns
-------
element or dict
If ``on_select`` is ``"ignore"`` (default), this command returns an
internal placeholder for the chart element. Otherwise, this method
returns a dictionary-like object that supports both key and
attribute notation. The attributes are described by the
``PydeckState`` dictionary schema.
Example
-------
Here's a chart using a HexagonLayer and a ScatterplotLayer. It uses either the
light or dark map style, based on which Streamlit theme is currently active:
>>> import pandas as pd
>>> import pydeck as pdk
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(
... rng(0).standard_normal((1000, 2)) / [50, 50] + [37.76, -122.4],
... columns=["lat", "lon"],
... )
>>>
>>> st.pydeck_chart(
... pdk.Deck(
... map_style=None, # Use Streamlit theme to pick map style
... initial_view_state=pdk.ViewState(
... latitude=37.76,
... longitude=-122.4,
... zoom=11,
... pitch=50,
... ),
... layers=[
... pdk.Layer(
... "HexagonLayer",
... data=df,
... get_position="[lon, lat]",
... radius=200,
... elevation_scale=4,
... elevation_range=[0, 1000],
... pickable=True,
... extruded=True,
... ),
... pdk.Layer(
... "ScatterplotLayer",
... data=df,
... get_position="[lon, lat]",
... get_color="[200, 30, 0, 160]",
... get_radius=200,
... ),
... ],
... )
... )
.. output::
https://doc-pydeck-chart.streamlit.app/
height: 530px
.. note::
To make the PyDeck chart's style consistent with Streamlit's theme,
you can set ``map_style=None`` in the ``pydeck.Deck`` object.
"""
if use_container_width is not None:
show_deprecation_warning(
make_deprecated_name_warning(
"use_container_width",
"width",
"2025-12-31",
"For `use_container_width=True`, use `width='stretch'`. "
"For `use_container_width=False`, specify an integer width.",
include_st_prefix=False,
),
show_in_browser=False,
)
if use_container_width:
width = "stretch"
# Otherwise keep the provided width.
validate_width(width, allow_content=False)
validate_height(height, allow_content=False)
pydeck_proto = PydeckProto()
ctx = get_script_run_ctx()
spec = json.dumps(EMPTY_MAP) if pydeck_obj is None else pydeck_obj.to_json()
pydeck_proto.json = spec
tooltip = _get_pydeck_tooltip(pydeck_obj)
if tooltip:
pydeck_proto.tooltip = json.dumps(tooltip)
# Get the Mapbox key from the PyDeck object first, and then fallback to the
# old mapbox.token config option.
mapbox_token = getattr(pydeck_obj, "mapbox_key", None)
if mapbox_token is None or mapbox_token == "":
mapbox_token = config.get_option("mapbox.token")
if mapbox_token:
pydeck_proto.mapbox_token = mapbox_token
key = to_key(key)
is_selection_activated = on_select != "ignore"
if on_select not in ["ignore", "rerun"] and not callable(on_select):
raise StreamlitAPIException(
f"You have passed {on_select} to `on_select`. "
"But only 'ignore', 'rerun', or a callable is supported."
)
if is_selection_activated:
# Selections are activated, treat Pydeck as a widget:
pydeck_proto.selection_mode.extend(parse_selection_mode(selection_mode))
# Run some checks that are only relevant when selections are activated
is_callback = callable(on_select)
check_widget_policies(
self.dg,
key,
on_change=cast("WidgetCallback", on_select) if is_callback else None,
default_value=None,
writes_allowed=False,
enable_check_callback_rules=is_callback,
)
pydeck_proto.form_id = current_form_id(self.dg)
pydeck_proto.id = compute_and_register_element_id(
"deck_gl_json_chart",
user_key=key,
key_as_main_identity=False,
dg=self.dg,
is_selection_activated=is_selection_activated,
selection_mode=selection_mode,
use_container_width=use_container_width,
spec=spec,
)
serde = PydeckSelectionSerde()
widget_state = register_widget(
pydeck_proto.id,
ctx=ctx,
deserializer=serde.deserialize,
on_change_handler=on_select if callable(on_select) else None,
serializer=serde.serialize,
value_type="string_value",
)
layout_config = LayoutConfig(width=width, height=height)
self.dg._enqueue(
"deck_gl_json_chart", pydeck_proto, layout_config=layout_config
)
return widget_state.value
layout_config = LayoutConfig(width=width, height=height)
return self.dg._enqueue(
"deck_gl_json_chart", pydeck_proto, layout_config=layout_config
)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
def _get_pydeck_width(pydeck_obj: Deck | None) -> int | None:
"""Extract the width from a pydeck Deck object, if specified."""
if pydeck_obj is None:
return None
width = getattr(pydeck_obj, "width", None)
if width is not None and isinstance(width, (int, float)):
return int(width)
return None
def _get_pydeck_tooltip(pydeck_obj: Deck | None) -> dict[str, str] | None:
if pydeck_obj is None:
return None
# For pydeck <0.8.1 or pydeck>=0.8.1 when jupyter extra is installed.
desk_widget = getattr(pydeck_obj, "deck_widget", None)
if desk_widget is not None and isinstance(desk_widget.tooltip, dict):
return desk_widget.tooltip
# For pydeck >=0.8.1 when jupyter extra is not installed.
# For details, see: https://github.com/visgl/deck.gl/pull/7125/files
tooltip = getattr(pydeck_obj, "_tooltip", None)
if tooltip is not None and isinstance(tooltip, dict):
return cast("dict[str, str]", tooltip)
return None
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/heading.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from enum import Enum
from typing import TYPE_CHECKING, Literal, TypeAlias, cast
from streamlit.elements.lib.layout_utils import LayoutConfig, validate_width
from streamlit.errors import StreamlitAPIException
from streamlit.proto.Heading_pb2 import Heading as HeadingProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.string_util import clean_text
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
from streamlit.elements.lib.layout_utils import TextAlignment, Width
from streamlit.type_util import SupportsStr
class HeadingProtoTag(Enum):
TITLE_TAG = "h1"
HEADER_TAG = "h2"
SUBHEADER_TAG = "h3"
Anchor: TypeAlias = str | Literal[False] | None
Divider: TypeAlias = bool | str | None
class HeadingMixin:
@gather_metrics("header")
def header(
self,
body: SupportsStr,
anchor: Anchor = None,
*, # keyword-only arguments:
help: str | None = None,
divider: Divider = False,
width: Width = "stretch",
text_alignment: TextAlignment = "left",
) -> DeltaGenerator:
"""Display text in header formatting.
Parameters
----------
body : str
The text to display as GitHub-flavored Markdown. Syntax
information can be found at: https://github.github.com/gfm.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
anchor : str or False
The anchor name of the header that can be accessed with #anchor
in the URL. If omitted, it generates an anchor using the body.
If False, the anchor is not shown in the UI.
help : str or None
A tooltip that gets displayed next to the header. If this is
``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
divider : bool, "blue", "green", "orange", "red", "violet", "yellow", "gray"/"grey", or "rainbow"
Shows a colored divider below the header. If this is ``True``,
successive headers will cycle through divider colors, except gray
and rainbow. That is, the first header will have a blue line, the
second header will have a green line, and so on. If this is a
string, the color can be set to one of the following: blue, green,
orange, red, violet, yellow, gray/grey, or rainbow.
width : "stretch", "content", or int
The width of the header element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- ``"content"``: The width of the element matches the width of its
content, but doesn't exceed the width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
text_alignment : "left", "center", "right", or "justify"
The horizontal alignment of the text within the element. This can
be one of the following:
- ``"left"`` (default): Text is aligned to the left edge.
- ``"center"``: Text is centered.
- ``"right"``: Text is aligned to the right edge.
- ``"justify"``: Text is justified (stretched to fill the available
width with the last line left-aligned).
.. note::
For text alignment to have a visible effect, the element's
width must be wider than its content. If you use
``width="content"`` with short text, the alignment may not be
noticeable.
Examples
--------
>>> import streamlit as st
>>>
>>> st.header("_Streamlit_ is :blue[cool] :sunglasses:")
>>> st.header("This is a header with a divider", divider="gray")
>>> st.header("These headers have rotating dividers", divider=True)
>>> st.header("One", divider=True)
>>> st.header("Two", divider=True)
>>> st.header("Three", divider=True)
>>> st.header("Four", divider=True)
.. output::
https://doc-header.streamlit.app/
height: 600px
"""
validate_width(width, allow_content=True)
layout_config = LayoutConfig(width=width, text_alignment=text_alignment)
return self.dg._enqueue(
"heading",
HeadingMixin._create_heading_proto(
tag=HeadingProtoTag.HEADER_TAG,
body=body,
anchor=anchor,
help=help,
divider=divider,
),
layout_config=layout_config,
)
@gather_metrics("subheader")
def subheader(
self,
body: SupportsStr,
anchor: Anchor = None,
*, # keyword-only arguments:
help: str | None = None,
divider: Divider = False,
width: Width = "stretch",
text_alignment: TextAlignment = "left",
) -> DeltaGenerator:
"""Display text in subheader formatting.
Parameters
----------
body : str
The text to display as GitHub-flavored Markdown. Syntax
information can be found at: https://github.github.com/gfm.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
anchor : str or False
The anchor name of the header that can be accessed with #anchor
in the URL. If omitted, it generates an anchor using the body.
If False, the anchor is not shown in the UI.
help : str or None
A tooltip that gets displayed next to the subheader. If this is
``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
divider : bool, "blue", "green", "orange", "red", "violet", "yellow", "gray"/"grey", or "rainbow"
Shows a colored divider below the header. If this is ``True``,
successive headers will cycle through divider colors, except gray
and rainbow. That is, the first header will have a blue line, the
second header will have a green line, and so on. If this is a
string, the color can be set to one of the following: blue, green,
orange, red, violet, yellow, gray/grey, or rainbow.
width : "stretch", "content", or int
The width of the subheader element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- ``"content"``: The width of the element matches the width of its
content, but doesn't exceed the width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
text_alignment : "left", "center", "right", or "justify"
The horizontal alignment of the text within the element. This can
be one of the following:
- ``"left"`` (default): Text is aligned to the left edge.
- ``"center"``: Text is centered.
- ``"right"``: Text is aligned to the right edge.
- ``"justify"``: Text is justified (stretched to fill the available
width with the last line left-aligned).
.. note::
For text alignment to have a visible effect, the element's
width must be wider than its content. If you use
``width="content"`` with short text, the alignment may not be
noticeable.
Examples
--------
>>> import streamlit as st
>>>
>>> st.subheader("_Streamlit_ is :blue[cool] :sunglasses:")
>>> st.subheader("This is a subheader with a divider", divider="gray")
>>> st.subheader("These subheaders have rotating dividers", divider=True)
>>> st.subheader("One", divider=True)
>>> st.subheader("Two", divider=True)
>>> st.subheader("Three", divider=True)
>>> st.subheader("Four", divider=True)
.. output::
https://doc-subheader.streamlit.app/
height: 500px
"""
validate_width(width, allow_content=True)
layout_config = LayoutConfig(width=width, text_alignment=text_alignment)
return self.dg._enqueue(
"heading",
HeadingMixin._create_heading_proto(
tag=HeadingProtoTag.SUBHEADER_TAG,
body=body,
anchor=anchor,
help=help,
divider=divider,
),
layout_config=layout_config,
)
@gather_metrics("title")
def title(
self,
body: SupportsStr,
anchor: Anchor = None,
*, # keyword-only arguments:
help: str | None = None,
width: Width = "stretch",
text_alignment: TextAlignment = "left",
) -> DeltaGenerator:
"""Display text in title formatting.
Each document should have a single `st.title()`, although this is not
enforced.
Parameters
----------
body : str
The text to display as GitHub-flavored Markdown. Syntax
information can be found at: https://github.github.com/gfm.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
anchor : str or False
The anchor name of the header that can be accessed with #anchor
in the URL. If omitted, it generates an anchor using the body.
If False, the anchor is not shown in the UI.
help : str or None
A tooltip that gets displayed next to the title. If this is
``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
width : "stretch", "content", or int
The width of the title element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- ``"content"``: The width of the element matches the width of its
content, but doesn't exceed the width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
text_alignment : "left", "center", "right", or "justify"
The horizontal alignment of the text within the element. This can
be one of the following:
- ``"left"`` (default): Text is aligned to the left edge.
- ``"center"``: Text is centered.
- ``"right"``: Text is aligned to the right edge.
- ``"justify"``: Text is justified (stretched to fill the available
width with the last line left-aligned).
.. note::
For text alignment to have a visible effect, the element's
width must be wider than its content. If you use
``width="content"`` with short text, the alignment may not be
noticeable.
Examples
--------
>>> import streamlit as st
>>>
>>> st.title("This is a title")
>>> st.title("_Streamlit_ is :blue[cool] :sunglasses:")
.. output::
https://doc-title.streamlit.app/
height: 220px
"""
validate_width(width, allow_content=True)
layout_config = LayoutConfig(width=width, text_alignment=text_alignment)
return self.dg._enqueue(
"heading",
HeadingMixin._create_heading_proto(
tag=HeadingProtoTag.TITLE_TAG,
body=body,
anchor=anchor,
help=help,
),
layout_config=layout_config,
)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
@staticmethod
def _handle_divider_color(divider: Divider) -> str:
if divider is True:
return "auto"
valid_colors = [
"red",
"orange",
"yellow",
"blue",
"green",
"violet",
"gray",
"grey",
"rainbow",
]
if divider in valid_colors:
return cast("str", divider)
raise StreamlitAPIException(
f"Divider parameter has invalid value: `{divider}`. Please choose from: {', '.join(valid_colors)}."
)
@staticmethod
def _create_heading_proto(
tag: HeadingProtoTag,
body: SupportsStr,
anchor: Anchor = None,
help: str | None = None,
divider: Divider = False,
) -> HeadingProto:
proto = HeadingProto()
proto.tag = tag.value
proto.body = clean_text(body)
if divider:
proto.divider = HeadingMixin._handle_divider_color(divider)
if anchor is not None:
if anchor is False:
proto.hide_anchor = True
elif isinstance(anchor, str):
proto.anchor = anchor
elif anchor is True: # type: ignore
raise StreamlitAPIException(
f"Anchor parameter has invalid value: {anchor}. "
"Supported values: None, any string or False"
)
else:
raise StreamlitAPIException(
f"Anchor parameter has invalid type: {type(anchor).__name__}. "
"Supported values: None, any string or False"
)
if help:
proto.help = help
return proto
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/html.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import os
import re
from pathlib import Path
from typing import TYPE_CHECKING, Any, cast
from streamlit.delta_generator_singletons import get_dg_singleton_instance
from streamlit.elements.lib.layout_utils import (
LayoutConfig,
Width,
validate_width,
)
from streamlit.errors import StreamlitAPIException
from streamlit.proto.Html_pb2 import Html as HtmlProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.string_util import clean_text
from streamlit.type_util import SupportsReprHtml, SupportsStr, has_callable_attr
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
class HtmlMixin:
@gather_metrics("html")
def html(
self,
body: str | Path | SupportsStr | SupportsReprHtml,
*, # keyword-only arguments:
width: Width = "stretch",
unsafe_allow_javascript: bool = False,
) -> DeltaGenerator:
"""Insert HTML into your app.
Adding custom HTML to your app impacts safety, styling, and
maintainability. We sanitize HTML with `DOMPurify
<https://github.com/cure53/DOMPurify>`_, but inserting HTML remains a
developer risk. Passing untrusted code to ``st.html`` or dynamically
loading external code can increase the risk of vulnerabilities in your
app.
``st.html`` content is **not** iframed. By default, JavaScript is
ignored. To execute JavaScript contained in your HTML, set
``unsafe_allow_javascript=True``. Use this with caution and never pass
untrusted input.
Parameters
----------
body : any
The HTML code to insert. This can be one of the following:
- A string of HTML code.
- A path to a local file with HTML code. The path can be a ``str``
or ``Path`` object. Paths can be absolute or relative to the
working directory (where you execute ``streamlit run``).
- Any object. If ``body`` is not a string or path, Streamlit will
convert the object to a string. ``body._repr_html_()`` takes
precedence over ``str(body)`` when available.
If the resulting HTML content is empty, Streamlit will raise an
error.
If ``body`` is a path to a CSS file, Streamlit will wrap the CSS
content in ``<style>`` tags automatically. When the resulting HTML
content only contains style tags, Streamlit will send the content
to the event container instead of the main container to avoid
taking up space in the app.
width : "stretch", "content", or int
The width of the HTML element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- ``"content"``: The width of the element matches the width of its
content, but doesn't exceed the width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
unsafe_allow_javascript : bool
Whether to execute JavaScript contained in your HTML. If this is
``False`` (default), JavaScript is ignored. If this is ``True``,
JavaScript is executed. Use this with caution and never pass
untrusted input.
Example
-------
>>> import streamlit as st
>>>
>>> st.html(
... "<p><span style='text-decoration: line-through double red;'>Oops</span>!</p>"
... )
.. output::
https://doc-html.streamlit.app/
height: 300px
"""
html_proto = HtmlProto()
# If body supports _repr_html_, use that.
if has_callable_attr(body, "_repr_html_"):
html_content = cast("SupportsReprHtml", body)._repr_html_()
# Check if the body is a file path. May include filesystem lookup.
elif isinstance(body, Path) or _is_file(body):
file_path = str(body)
with open(file_path, encoding="utf-8") as f:
html_content = f.read()
# If it's a CSS file, wrap the content in style tags
if Path(file_path).suffix.lower() == ".css":
html_content = f"<style>{html_content}</style>"
# OK, let's just try converting to string and hope for the best.
else:
html_content = clean_text(cast("SupportsStr", body))
# Raise an error if the body is empty
if html_content == "":
raise StreamlitAPIException("`st.html` body cannot be empty")
validate_width(width, allow_content=True)
layout_config = LayoutConfig(width=width)
# Handle the case where there are only style tags - issue #9388
# Use event container for style tags so they don't take up space in the app content
if _html_only_style_tags(html_content):
# If true, there are only style tags - send html to the event container
html_proto.body = html_content
return self._event_dg._enqueue("html", html_proto)
# Otherwise, send the html to the main container as normal
# Only set the unsafe JS flag for non-style-only HTML content
html_proto.unsafe_allow_javascript = unsafe_allow_javascript
html_proto.body = html_content
return self.dg._enqueue("html", html_proto, layout_config=layout_config)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
@property
def _event_dg(self) -> DeltaGenerator:
"""Get the event delta generator."""
return get_dg_singleton_instance().event_dg
def _html_only_style_tags(html_content: str) -> bool:
"""Check if the HTML content is only style tags."""
# Pattern to match HTML comments
comment_pattern = r"<!--.*?-->"
# Pattern to match style tags and their contents (case-insensitive)
style_pattern = r"<style[^>]*>.*?</style>"
# Remove style tags and comments
html_without_comments = re.sub(comment_pattern, "", html_content, flags=re.DOTALL)
html_without_styles_and_comments = re.sub(
style_pattern, "", html_without_comments, flags=re.DOTALL | re.IGNORECASE
)
# Return whether html content is empty after removing style tags and comments
return html_without_styles_and_comments.strip() == ""
def _is_file(obj: Any) -> bool:
"""Checks if obj is a file, and doesn't throw if not.
The "not throwing" part is important!
"""
try:
return os.path.isfile(obj)
except TypeError:
return False
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/spinner.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import contextlib
import threading
from typing import TYPE_CHECKING, Final, cast
from streamlit.elements.lib.layout_utils import (
LayoutConfig,
Width,
validate_width,
)
from streamlit.runtime.scriptrunner import add_script_run_ctx
if TYPE_CHECKING:
from collections.abc import Iterator
from streamlit.delta_generator import DeltaGenerator
# Set the message 0.5 seconds in the future to avoid annoying
# flickering if this spinner runs too quickly.
DELAY_SECS: Final = 0.5
class SpinnerMixin:
@contextlib.contextmanager
def spinner(
self,
text: str = "In progress...",
*,
show_time: bool = False,
_cache: bool = False,
width: Width = "content",
) -> Iterator[None]:
"""Display a loading spinner while executing a block of code.
Parameters
----------
text : str
The text to display next to the spinner. This defaults to
``"In progress..."``.
The text can optionally contain GitHub-flavored Markdown. Syntax
information can be found at: https://github.github.com/gfm.
See the ``body`` parameter of |st.markdown|_ for additional, supported
Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
show_time : bool
Whether to show the elapsed time next to the spinner text. If this is
``False`` (default), no time is displayed. If this is ``True``,
elapsed time is displayed with a precision of 0.1 seconds. The time
format is not configurable.
width : "content", "stretch", or int
The width of the spinner element. This can be one of the following:
- ``"content"`` (default): The width of the element matches the
width of its content, but doesn't exceed the width of the parent
container.
- ``"stretch"``: The width of the element matches the width of the
parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
Example
-------
>>> import streamlit as st
>>> import time
>>>
>>> with st.spinner("Wait for it...", show_time=True):
>>> time.sleep(5)
>>> st.success("Done!")
>>> st.button("Rerun")
.. output::
https://doc-spinner.streamlit.app/
height: 210px
"""
from streamlit.proto.Spinner_pb2 import Spinner as SpinnerProto
from streamlit.string_util import clean_text
validate_width(width, allow_content=True)
layout_config = LayoutConfig(width=width)
message = self.dg.empty()
display_message = True
display_message_lock = threading.Lock()
try:
def set_message() -> None:
with display_message_lock:
if display_message:
spinner_proto = SpinnerProto()
spinner_proto.text = clean_text(text)
spinner_proto.cache = _cache
spinner_proto.show_time = show_time
message._enqueue(
"spinner", spinner_proto, layout_config=layout_config
)
add_script_run_ctx(threading.Timer(DELAY_SECS, set_message)).start()
# Yield control back to the context.
yield
finally:
if display_message_lock:
with display_message_lock:
display_message = False
if "chat_message" in set(message._active_dg._ancestor_block_types):
# Temporary stale element fix:
# For chat messages, we are resetting the spinner placeholder to an
# empty container instead of an empty placeholder (st.empty) to have
# it removed from the delta path. Empty containers are ignored in the
# frontend since they are configured with allow_empty=False. This
# prevents issues with stale elements caused by the spinner being
# rendered only in some situations (e.g. for caching).
message.container()
else:
message.empty()
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/text.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from typing import TYPE_CHECKING, cast
from streamlit.elements.lib.layout_utils import LayoutConfig, validate_width
from streamlit.proto.Text_pb2 import Text as TextProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.string_util import clean_text
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
from streamlit.elements.lib.layout_utils import TextAlignment, Width
from streamlit.type_util import SupportsStr
class TextMixin:
@gather_metrics("text")
def text(
self,
body: SupportsStr,
*, # keyword-only arguments:
help: str | None = None,
width: Width = "content",
text_alignment: TextAlignment = "left",
) -> DeltaGenerator:
r"""Write text without Markdown or HTML parsing.
For monospace text, use |st.code|_.
.. |st.code| replace:: ``st.code``
.. _st.code: https://docs.streamlit.io/develop/api-reference/text/st.code
Parameters
----------
body : str
The string to display.
help : str or None
A tooltip that gets displayed next to the text. If this is ``None``
(default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
width : "content", "stretch", or int
The width of the text element. This can be one of the following:
- ``"content"`` (default): The width of the element matches the
width of its content, but doesn't exceed the width of the parent
container.
- ``"stretch"``: The width of the element matches the width of the
parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
text_alignment : "left", "center", "right", or "justify"
The horizontal alignment of the text within the element. This can
be one of the following:
- ``"left"`` (default): Text is aligned to the left edge.
- ``"center"``: Text is centered.
- ``"right"``: Text is aligned to the right edge.
- ``"justify"``: Text is justified (stretched to fill the available
width with the last line left-aligned).
.. note::
For text alignment to have a visible effect, the element's
width must be wider than its content. If you use
``width="content"`` with short text, the alignment may not be
noticeable.
Example
-------
>>> import streamlit as st
>>>
>>> st.text("This is text\n[and more text](that's not a Markdown link).")
.. output::
https://doc-text.streamlit.app/
height: 220px
"""
text_proto = TextProto()
text_proto.body = clean_text(body)
if help:
text_proto.help = help
validate_width(width, allow_content=True)
layout_config = LayoutConfig(width=width, text_alignment=text_alignment)
return self.dg._enqueue("text", text_proto, layout_config=layout_config)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/plotly_chart.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import json
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
Any,
Final,
Literal,
TypeAlias,
TypedDict,
Union,
cast,
overload,
)
from typing_extensions import Required
from streamlit import type_util
from streamlit.deprecation_util import (
make_deprecated_name_warning,
show_deprecation_warning,
)
from streamlit.elements.lib.form_utils import current_form_id
from streamlit.elements.lib.layout_utils import (
Height,
LayoutConfig,
Width,
validate_height,
validate_width,
)
from streamlit.elements.lib.policies import check_widget_policies
from streamlit.elements.lib.streamlit_plotly_theme import (
configure_streamlit_plotly_theme,
)
from streamlit.elements.lib.utils import Key, compute_and_register_element_id, to_key
from streamlit.errors import StreamlitAPIException
from streamlit.logger import get_logger
from streamlit.proto.PlotlyChart_pb2 import PlotlyChart as PlotlyChartProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner_utils.script_run_context import get_script_run_ctx
from streamlit.runtime.state import WidgetCallback, register_widget
from streamlit.util import AttributeDictionary
if TYPE_CHECKING:
from collections.abc import Iterable
import matplotlib as mpl
import plotly.graph_objs as go
from plotly.basedatatypes import BaseFigure
from streamlit.delta_generator import DeltaGenerator
# We need to configure the Plotly theme before any Plotly figures are created:
configure_streamlit_plotly_theme()
_AtomicFigureOrData: TypeAlias = Union[
"go.Figure",
"go.Data",
]
FigureOrData: TypeAlias = Union[
_AtomicFigureOrData,
list[_AtomicFigureOrData],
# It is kind of hard to figure out exactly what kind of dict is supported
# here, as plotly hasn't embraced typing yet. This version is chosen to
# align with the docstring.
dict[str, _AtomicFigureOrData],
"BaseFigure",
"mpl.figure.Figure",
]
SelectionMode: TypeAlias = Literal["lasso", "points", "box"]
_SELECTION_MODES: Final[set[SelectionMode]] = {"lasso", "points", "box"}
_LOGGER: Final = get_logger(__name__)
class PlotlySelectionState(TypedDict, total=False):
"""
The schema for the Plotly chart selection state.
The selection state is stored in a dictionary-like object that supports both
key and attribute notation. Selection states cannot be programmatically
changed or set through Session State.
Attributes
----------
points : list[dict[str, Any]]
The selected data points in the chart, including the data points
selected by the box and lasso mode. The data includes the values
associated to each point and a point index used to populate
``point_indices``. If additional information has been assigned to your
points, such as size or legend group, this is also included.
point_indices : list[int]
The numerical indices of all selected data points in the chart. The
details of each identified point are included in ``points``.
box : list[dict[str, Any]]
The metadata related to the box selection. This includes the
coordinates of the selected area.
lasso : list[dict[str, Any]]
The metadata related to the lasso selection. This includes the
coordinates of the selected area.
Example
-------
When working with more complicated graphs, the ``points`` attribute
displays additional information. Try selecting points in the following
example:
>>> import plotly.express as px
>>> import streamlit as st
>>>
>>> df = px.data.iris()
>>> fig = px.scatter(
... df,
... x="sepal_width",
... y="sepal_length",
... color="species",
... size="petal_length",
... hover_data=["petal_width"],
... )
>>>
>>> event = st.plotly_chart(fig, key="iris", on_select="rerun")
>>>
>>> event.selection
.. output::
https://doc-chart-events-plotly-selection-state.streamlit.app
height: 600px
This is an example of the selection state when selecting a single point:
>>> {
>>> "points": [
>>> {
>>> "curve_number": 2,
>>> "point_number": 9,
>>> "point_index": 9,
>>> "x": 3.6,
>>> "y": 7.2,
>>> "customdata": [
>>> 2.5
>>> ],
>>> "marker_size": 6.1,
>>> "legendgroup": "virginica"
>>> }
>>> ],
>>> "point_indices": [
>>> 9
>>> ],
>>> "box": [],
>>> "lasso": []
>>> }
"""
points: Required[list[dict[str, Any]]]
point_indices: Required[list[int]]
box: Required[list[dict[str, Any]]]
lasso: Required[list[dict[str, Any]]]
class PlotlyState(TypedDict, total=False):
"""
The schema for the Plotly chart event state.
The event state is stored in a dictionary-like object that supports both
key and attribute notation. Event states cannot be programmatically
changed or set through Session State.
Only selection events are supported at this time.
Attributes
----------
selection : dict
The state of the ``on_select`` event. This attribute returns a
dictionary-like object that supports both key and attribute notation.
The attributes are described by the ``PlotlySelectionState`` dictionary
schema.
Example
-------
Try selecting points by any of the three available methods (direct click,
box, or lasso). The current selection state is available through Session
State or as the output of the chart function.
>>> import plotly.express as px
>>> import streamlit as st
>>>
>>> df = px.data.iris()
>>> fig = px.scatter(df, x="sepal_width", y="sepal_length")
>>>
>>> event = st.plotly_chart(fig, key="iris", on_select="rerun")
>>>
>>> event
.. output::
https://doc-chart-events-plotly-state.streamlit.app
height: 600px
"""
selection: Required[PlotlySelectionState]
@dataclass
class PlotlyChartSelectionSerde:
"""PlotlyChartSelectionSerde is used to serialize and deserialize the Plotly Chart
selection state.
"""
def deserialize(self, ui_value: str | None) -> PlotlyState:
empty_selection_state: PlotlyState = {
"selection": {
"points": [],
"point_indices": [],
"box": [],
"lasso": [],
},
}
selection_state = (
empty_selection_state
if ui_value is None
else cast("PlotlyState", AttributeDictionary(json.loads(ui_value)))
)
if "selection" not in selection_state:
selection_state = empty_selection_state # type: ignore[unreachable]
return cast("PlotlyState", AttributeDictionary(selection_state))
def serialize(self, selection_state: PlotlyState) -> str:
return json.dumps(selection_state, default=str)
def parse_selection_mode(
selection_mode: SelectionMode | Iterable[SelectionMode],
) -> set[PlotlyChartProto.SelectionMode.ValueType]:
"""Parse and check the user provided selection modes."""
if isinstance(selection_mode, str):
# Only a single selection mode was passed
selection_mode_set = {selection_mode}
else:
# Multiple selection modes were passed
selection_mode_set = set(selection_mode)
if not selection_mode_set.issubset(_SELECTION_MODES):
raise StreamlitAPIException(
f"Invalid selection mode: {selection_mode}. "
f"Valid options are: {_SELECTION_MODES}"
)
parsed_selection_modes = []
for mode in selection_mode_set:
if mode == "points":
parsed_selection_modes.append(PlotlyChartProto.SelectionMode.POINTS)
elif mode == "lasso":
parsed_selection_modes.append(PlotlyChartProto.SelectionMode.LASSO)
elif mode == "box":
parsed_selection_modes.append(PlotlyChartProto.SelectionMode.BOX)
return set(parsed_selection_modes)
def _resolve_content_width(width: Width, figure: Any) -> Width:
"""Resolve "content" width by inspecting the figure's layout width.
For content width, we check if the plotly figure has an explicit width
in its layout. If so, we use that as a pixel width. If not, we default
to 700 pixels which matches the plotly.js default width.
Args
----
width : Width
The original width parameter
figure : Any
The plotly figure object (Figure, dict, or other supported formats)
Returns
-------
Width
The resolved width (either original width, figure width as pixels, or 700)
"""
if width != "content":
return width
# Extract width from the figure's layout
# plotly.tools.mpl_to_plotly() returns Figure objects with .layout attribute
# plotly.tools.return_figure_from_figure_or_data() returns dictionaries
figure_width = None
if isinstance(figure, dict):
figure_width = figure.get("layout", {}).get("width")
else:
# Handle Figure objects from matplotlib conversion
try:
figure_width = figure.layout.width
except (AttributeError, TypeError):
_LOGGER.debug("Could not parse width from figure")
if (
figure_width is not None
and isinstance(figure_width, (int, float))
and figure_width > 0
):
return int(figure_width)
# Default to 700 pixels (plotly.js default) when no width is specified
return 700
def _resolve_content_height(height: Height, figure: Any) -> Height:
"""Resolve "content" height by inspecting the figure's layout height.
For content height, we check if the plotly figure has an explicit height
in its layout. If so, we use that as a pixel height. If not, we default
to 450 pixels which matches the plotly.js default height.
Args
----
height : Height
The original height parameter
figure : Any
The plotly figure object (Figure, dict, or other supported formats)
Returns
-------
Height
The resolved height (either original height, figure height as pixels, or 450)
"""
if height != "content":
return height
# Extract height from the figure's layout
# plotly.tools.mpl_to_plotly() returns Figure objects with .layout attribute
# plotly.tools.return_figure_from_figure_or_data() returns dictionaries
figure_height = None
if isinstance(figure, dict):
figure_height = figure.get("layout", {}).get("height")
else:
# Handle Figure objects from matplotlib conversion
try:
figure_height = figure.layout.height
except (AttributeError, TypeError):
_LOGGER.debug("Could not parse height from figure")
if (
figure_height is not None
and isinstance(figure_height, (int, float))
and figure_height > 0
):
return int(figure_height)
# Default to 450 pixels (plotly.js default) when no height is specified
return 450
class PlotlyMixin:
@overload
def plotly_chart(
self,
figure_or_data: FigureOrData,
use_container_width: bool | None = None,
*,
width: Width = "stretch",
height: Height = "content",
theme: Literal["streamlit"] | None = "streamlit",
key: Key | None = None,
on_select: Literal["ignore"], # No default value here to make it work with mypy
selection_mode: SelectionMode | Iterable[SelectionMode] = (
"points",
"box",
"lasso",
),
**kwargs: Any,
) -> DeltaGenerator: ...
@overload
def plotly_chart(
self,
figure_or_data: FigureOrData,
use_container_width: bool | None = None,
*,
width: Width = "stretch",
height: Height = "content",
theme: Literal["streamlit"] | None = "streamlit",
key: Key | None = None,
on_select: Literal["rerun"] | WidgetCallback = "rerun",
selection_mode: SelectionMode | Iterable[SelectionMode] = (
"points",
"box",
"lasso",
),
**kwargs: Any,
) -> PlotlyState: ...
@gather_metrics("plotly_chart")
def plotly_chart(
self,
figure_or_data: FigureOrData,
use_container_width: bool | None = None,
*,
width: Width = "stretch",
height: Height = "content",
theme: Literal["streamlit"] | None = "streamlit",
key: Key | None = None,
on_select: Literal["rerun", "ignore"] | WidgetCallback = "ignore",
selection_mode: SelectionMode | Iterable[SelectionMode] = (
"points",
"box",
"lasso",
),
config: dict[str, Any] | None = None,
**kwargs: Any,
) -> DeltaGenerator | PlotlyState:
"""Display an interactive Plotly chart.
`Plotly <https://plot.ly/python>`_ is a charting library for Python.
The arguments to this function closely follow the ones for Plotly's
``plot()`` function.
To show Plotly charts in Streamlit, call ``st.plotly_chart`` wherever
you would call Plotly's ``py.plot`` or ``py.iplot``.
.. Important::
You must install ``plotly>=4.0.0`` to use this command. Your app's
performance may be enhanced by installing ``orjson`` as well. You
can install all charting dependencies (except Bokeh) as an extra
with Streamlit:
.. code-block:: shell
pip install streamlit[charts]
Parameters
----------
figure_or_data : plotly.graph_objs.Figure, plotly.graph_objs.Data,\
or dict/list of plotly.graph_objs.Figure/Data
The Plotly ``Figure`` or ``Data`` object to render. See
https://plot.ly/python/ for examples of graph descriptions.
.. note::
If your chart contains more than 1000 data points, Plotly will
use a WebGL renderer to display the chart. Different browsers
have different limits on the number of WebGL contexts per page.
If you have multiple WebGL contexts on a page, you may need to
switch to SVG rendering mode. You can do this by setting
``render_mode="svg"`` within the figure. For example, the
following code defines a Plotly Express line chart that will
render in SVG mode when passed to ``st.plotly_chart``:
``px.line(df, x="x", y="y", render_mode="svg")``.
width : "stretch", "content", or int
The width of the chart element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- ``"content"``: The width of the element matches the width of its
content, but doesn't exceed the width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
height : "content", "stretch", or int
The height of the chart element. This can be one of the following:
- ``"content"`` (default): The height of the element matches the
height of its content.
- ``"stretch"``: The height of the element matches the height of
its content or the height of the parent container, whichever is
larger. If the element is not in a parent container, the height
of the element matches the height of its content.
- An integer specifying the height in pixels: The element has a
fixed height. If the content is larger than the specified
height, scrolling is enabled.
use_container_width : bool or None
Whether to override the figure's native width with the width of
the parent container. This can be one of the following:
- ``None`` (default): Streamlit will use the value of ``width``.
- ``True``: Streamlit sets the width of the figure to match the
width of the parent container.
- ``False``: Streamlit sets the width of the figure to fit its
contents according to the plotting library, up to the width of
the parent container.
.. deprecated::
``use_container_width`` is deprecated and will be removed in a
future release. For ``use_container_width=True``, use
``width="stretch"``.
theme : "streamlit" or None
The theme of the chart. If ``theme`` is ``"streamlit"`` (default),
Streamlit uses its own design default. If ``theme`` is ``None``,
Streamlit falls back to the default behavior of the library.
The ``"streamlit"`` theme can be partially customized through the
configuration options ``theme.chartCategoricalColors`` and
``theme.chartSequentialColors``. Font configuration options are
also applied.
key : str
An optional string to use for giving this element a stable
identity. If ``key`` is ``None`` (default), this element's identity
will be determined based on the values of the other parameters.
Additionally, if selections are activated and ``key`` is provided,
Streamlit will register the key in Session State to store the
selection state. The selection state is read-only.
on_select : "ignore" or "rerun" or callable
How the figure should respond to user selection events. This
controls whether or not the figure behaves like an input widget.
``on_select`` can be one of the following:
- ``"ignore"`` (default): Streamlit will not react to any selection
events in the chart. The figure will not behave like an input
widget.
- ``"rerun"``: Streamlit will rerun the app when the user selects
data in the chart. In this case, ``st.plotly_chart`` will return
the selection data as a dictionary.
- A ``callable``: Streamlit will rerun the app and execute the
``callable`` as a callback function before the rest of the app.
In this case, ``st.plotly_chart`` will return the selection data
as a dictionary.
selection_mode : "points", "box", "lasso" or an Iterable of these
The selection mode of the chart. This can be one of the following:
- ``"points"``: The chart will allow selections based on individual
data points.
- ``"box"``: The chart will allow selections based on rectangular
areas.
- ``"lasso"``: The chart will allow selections based on freeform
areas.
- An ``Iterable`` of the above options: The chart will allow
selections based on the modes specified.
All selections modes are activated by default.
config : dict or None
A dictionary of Plotly configuration options. This is passed to
Plotly's ``show()`` function. For more information about Plotly
configuration options, see Plotly's documentation on `Configuration
in Python <https://plotly.com/python/configuration-options/>`_.
**kwargs
Additional arguments accepted by Plotly's ``plot()`` function.
This supports ``config``, a dictionary of Plotly configuration
options. For more information about Plotly configuration options,
see Plotly's documentation on `Configuration in Python
<https://plotly.com/python/configuration-options/>`_.
.. deprecated::
``**kwargs`` are deprecated and will be removed in a future
release. Use ``config`` instead.
Returns
-------
element or dict
If ``on_select`` is ``"ignore"`` (default), this command returns an
internal placeholder for the chart element. Otherwise, this command
returns a dictionary-like object that supports both key and
attribute notation. The attributes are described by the
``PlotlyState`` dictionary schema.
Examples
--------
**Example 1: Basic Plotly chart**
The example below comes from the examples at https://plot.ly/python.
Note that ``plotly.figure_factory`` requires ``scipy`` to run.
>>> import plotly.figure_factory as ff
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> hist_data = [
... rng(0).standard_normal(200) - 2,
... rng(1).standard_normal(200),
... rng(2).standard_normal(200) + 2,
... ]
>>> group_labels = ["Group 1", "Group 2", "Group 3"]
>>>
>>> fig = ff.create_distplot(
... hist_data, group_labels, bin_size=[0.1, 0.25, 0.5]
... )
>>>
>>> st.plotly_chart(fig)
.. output::
https://doc-plotly-chart.streamlit.app/
height: 550px
**Example 2: Plotly Chart with configuration**
By default, Plotly charts have scroll zoom enabled. If you have a
longer page and want to avoid conflicts between page scrolling and
zooming, you can use Plotly's configuration options to disable scroll
zoom. In the following example, scroll zoom is disabled, but the zoom
buttons are still enabled in the modebar.
>>> import plotly.graph_objects as go
>>> import streamlit as st
>>>
>>> fig = go.Figure()
>>> fig.add_trace(
... go.Scatter(
... x=[1, 2, 3, 4, 5],
... y=[1, 3, 2, 5, 4]
... )
... )
>>>
>>> st.plotly_chart(fig, config = {'scrollZoom': False})
.. output::
https://doc-plotly-chart-config.streamlit.app/
height: 550px
"""
if use_container_width is not None:
show_deprecation_warning(
make_deprecated_name_warning(
"use_container_width",
"width",
"2025-12-31",
"For `use_container_width=True`, use `width='stretch'`. "
"For `use_container_width=False`, use `width='content'`.",
include_st_prefix=False,
),
show_in_browser=False,
)
if use_container_width:
width = "stretch"
elif not isinstance(width, int):
width = "content"
validate_width(width, allow_content=True)
validate_height(height, allow_content=True)
import plotly.io
import plotly.tools
# NOTE: "figure_or_data" is the name used in Plotly's .plot() method
# for their main parameter. I don't like the name, but it's best to
# keep it in sync with what Plotly calls it.
if kwargs:
show_deprecation_warning(
"Variable keyword arguments for `st.plotly_chart` have been "
"deprecated and will be removed in a future release. Use the "
"`config` argument instead to specify Plotly configuration "
"options."
)
if theme not in ["streamlit", None]:
raise StreamlitAPIException(
f'You set theme="{theme}" while Streamlit charts only support '
"theme=”streamlit” or theme=None to fallback to the default "
"library theme."
)
if on_select not in ["ignore", "rerun"] and not callable(on_select):
raise StreamlitAPIException(
f"You have passed {on_select} to `on_select`. But only 'ignore', "
"'rerun', or a callable is supported."
)
key = to_key(key)
is_selection_activated = on_select != "ignore"
if is_selection_activated:
# Run some checks that are only relevant when selections are activated
is_callback = callable(on_select)
check_widget_policies(
self.dg,
key,
on_change=cast("WidgetCallback", on_select) if is_callback else None,
default_value=None,
writes_allowed=False,
enable_check_callback_rules=is_callback,
)
if type_util.is_type(figure_or_data, "matplotlib.figure.Figure"):
# Convert matplotlib figure to plotly figure:
figure = plotly.tools.mpl_to_plotly(figure_or_data)
else:
figure = plotly.tools.return_figure_from_figure_or_data(
figure_or_data, validate_figure=True
)
plotly_chart_proto = PlotlyChartProto()
plotly_chart_proto.theme = theme or ""
plotly_chart_proto.form_id = current_form_id(self.dg)
config = config or {}
plotly_chart_proto.spec = plotly.io.to_json(figure, validate=False)
plotly_chart_proto.config = json.dumps(config)
ctx = get_script_run_ctx()
# We are computing the widget id for all plotly uses
# to also allow non-widget Plotly charts to keep their state
# when the frontend component gets unmounted and remounted.
plotly_chart_proto.id = compute_and_register_element_id(
"plotly_chart",
user_key=key,
key_as_main_identity=False,
dg=self.dg,
plotly_spec=plotly_chart_proto.spec,
plotly_config=plotly_chart_proto.config,
selection_mode=selection_mode,
is_selection_activated=is_selection_activated,
theme=theme,
width=width,
height=height,
)
# Handle "content" width and height by inspecting the figure's natural dimensions
final_width = _resolve_content_width(width, figure)
final_height = _resolve_content_height(height, figure)
if is_selection_activated:
# Selections are activated, treat plotly chart as a widget:
plotly_chart_proto.selection_mode.extend(
parse_selection_mode(selection_mode)
)
serde = PlotlyChartSelectionSerde()
widget_state = register_widget(
plotly_chart_proto.id,
on_change_handler=on_select if callable(on_select) else None,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="string_value",
)
layout_config = LayoutConfig(width=final_width, height=final_height)
self.dg._enqueue(
"plotly_chart", plotly_chart_proto, layout_config=layout_config
)
return widget_state.value
layout_config = LayoutConfig(width=final_width, height=final_height)
return self.dg._enqueue(
"plotly_chart", plotly_chart_proto, layout_config=layout_config
)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/media.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import io
import re
from datetime import timedelta
from pathlib import Path
from typing import TYPE_CHECKING, Final, TypeAlias, Union, cast
from streamlit import runtime, type_util, url_util
from streamlit.elements.lib.layout_utils import WidthWithoutContent, validate_width
from streamlit.elements.lib.subtitle_utils import process_subtitle_data
from streamlit.elements.lib.utils import compute_and_register_element_id
from streamlit.errors import StreamlitAPIException
from streamlit.proto.Audio_pb2 import Audio as AudioProto
from streamlit.proto.Video_pb2 import Video as VideoProto
from streamlit.proto.WidthConfig_pb2 import WidthConfig
from streamlit.runtime import caching
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.time_util import time_to_seconds
if TYPE_CHECKING:
from typing import Any
from numpy import typing as npt
from streamlit.delta_generator import DeltaGenerator
MediaData: TypeAlias = Union[
str,
Path,
bytes,
io.BytesIO,
io.RawIOBase,
io.BufferedReader,
"npt.NDArray[Any]",
None,
]
SubtitleData: TypeAlias = (
str | Path | bytes | io.BytesIO | dict[str, str | Path | bytes | io.BytesIO] | None
)
MediaTime: TypeAlias = int | float | timedelta | str
TIMEDELTA_PARSE_ERROR_MESSAGE: Final = (
"Failed to convert '{param_name}' to a timedelta. "
"Please use a string in a format supported by "
"[Pandas Timedelta constructor]"
"(https://pandas.pydata.org/docs/reference/api/pandas.Timedelta.html), "
'e.g. `"10s"`, `"15 seconds"`, or `"1h23s"`. Got: {param_value}'
)
class MediaMixin:
@gather_metrics("audio")
def audio(
self,
data: MediaData,
format: str = "audio/wav",
start_time: MediaTime = 0,
*,
sample_rate: int | None = None,
end_time: MediaTime | None = None,
loop: bool = False,
autoplay: bool = False,
width: WidthWithoutContent = "stretch",
) -> DeltaGenerator:
"""Display an audio player.
Parameters
----------
data : str, Path, bytes, BytesIO, numpy.ndarray, or file
The audio to play. This can be one of the following:
- A URL (string) for a hosted audio file.
- A path to a local audio file. The path can be a ``str``
or ``Path`` object. Paths can be absolute or relative to the
working directory (where you execute ``streamlit run``).
- Raw audio data. Raw data formats must include all necessary file
headers to match the file format specified via ``format``.
If ``data`` is a NumPy array, it must either be a 1D array of the
waveform or a 2D array of shape (C, S) where C is the number of
channels and S is the number of samples. See the default channel
order at
http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx
format : str
The MIME type for the audio file. This defaults to ``"audio/wav"``.
For more information about MIME types, see
https://www.iana.org/assignments/media-types/media-types.xhtml.
start_time : int, float, timedelta, str, or None
The time from which the element should start playing. This can be
one of the following:
- ``None`` (default): The element plays from the beginning.
- An ``int`` or ``float`` specifying the time in seconds. ``float``
values are rounded down to whole seconds.
- A string specifying the time in a format supported by `Pandas'
Timedelta constructor <https://pandas.pydata.org/docs/reference/api/pandas.Timedelta.html>`_,
e.g. ``"2 minute"``, ``"20s"``, or ``"1m14s"``.
- A ``timedelta`` object from `Python's built-in datetime library
<https://docs.python.org/3/library/datetime.html#timedelta-objects>`_,
e.g. ``timedelta(seconds=70)``.
sample_rate : int or None
The sample rate of the audio data in samples per second. This is
only required if ``data`` is a NumPy array.
end_time : int, float, timedelta, str, or None
The time at which the element should stop playing. This can be
one of the following:
- ``None`` (default): The element plays through to the end.
- An ``int`` or ``float`` specifying the time in seconds. ``float``
values are rounded down to whole seconds.
- A string specifying the time in a format supported by `Pandas'
Timedelta constructor <https://pandas.pydata.org/docs/reference/api/pandas.Timedelta.html>`_,
e.g. ``"2 minute"``, ``"20s"``, or ``"1m14s"``.
- A ``timedelta`` object from `Python's built-in datetime library
<https://docs.python.org/3/library/datetime.html#timedelta-objects>`_,
e.g. ``timedelta(seconds=70)``.
loop : bool
Whether the audio should loop playback.
autoplay : bool
Whether the audio file should start playing automatically. This is
``False`` by default. Browsers will not autoplay audio files if the
user has not interacted with the page by clicking somewhere.
width : "stretch" or int
The width of the audio player element. This can be one of the
following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
Examples
--------
To display an audio player for a local file, specify the file's string
path and format.
>>> import streamlit as st
>>>
>>> st.audio("cat-purr.mp3", format="audio/mpeg", loop=True)
.. output::
https://doc-audio-purr.streamlit.app/
height: 250px
You can also pass ``bytes`` or ``numpy.ndarray`` objects to ``st.audio``.
>>> import streamlit as st
>>> import numpy as np
>>>
>>> audio_file = open("myaudio.ogg", "rb")
>>> audio_bytes = audio_file.read()
>>>
>>> st.audio(audio_bytes, format="audio/ogg")
>>>
>>> sample_rate = 44100 # 44100 samples per second
>>> seconds = 2 # Note duration of 2 seconds
>>> frequency_la = 440 # Our played note will be 440 Hz
>>> # Generate array with seconds*sample_rate steps, ranging between 0 and seconds
>>> t = np.linspace(0, seconds, seconds * sample_rate, False)
>>> # Generate a 440 Hz sine wave
>>> note_la = np.sin(frequency_la * t * 2 * np.pi)
>>>
>>> st.audio(note_la, sample_rate=sample_rate)
.. output::
https://doc-audio.streamlit.app/
height: 865px
"""
start_time, end_time = _parse_start_time_end_time(start_time, end_time)
validate_width(width)
audio_proto = AudioProto()
is_data_numpy_array = type_util.is_type(data, "numpy.ndarray")
if is_data_numpy_array and sample_rate is None:
raise StreamlitAPIException(
"`sample_rate` must be specified when `data` is a numpy array."
)
if not is_data_numpy_array and sample_rate is not None:
self.dg.warning(
"Warning: `sample_rate` will be ignored since data is not a numpy "
"array."
)
coordinates = self.dg._get_delta_path_str()
marshall_audio(
self.dg,
coordinates,
audio_proto,
data,
format,
start_time,
sample_rate,
end_time,
loop,
autoplay,
width=width,
)
return self.dg._enqueue("audio", audio_proto)
@gather_metrics("video")
def video(
self,
data: MediaData,
format: str = "video/mp4",
start_time: MediaTime = 0,
*, # keyword-only arguments:
subtitles: SubtitleData = None,
end_time: MediaTime | None = None,
loop: bool = False,
autoplay: bool = False,
muted: bool = False,
width: WidthWithoutContent = "stretch",
) -> DeltaGenerator:
"""Display a video player.
Parameters
----------
data : str, Path, bytes, io.BytesIO, numpy.ndarray, or file
The video to play. This can be one of the following:
- A URL (string) for a hosted video file, including YouTube URLs.
- A path to a local video file. The path can be a ``str``
or ``Path`` object. Paths can be absolute or relative to the
working directory (where you execute ``streamlit run``).
- Raw video data. Raw data formats must include all necessary file
headers to match the file format specified via ``format``.
format : str
The MIME type for the video file. This defaults to ``"video/mp4"``.
For more information about MIME types, see
https://www.iana.org/assignments/media-types/media-types.xhtml.
start_time : int, float, timedelta, str, or None
The time from which the element should start playing. This can be
one of the following:
- ``None`` (default): The element plays from the beginning.
- An ``int`` or ``float`` specifying the time in seconds. ``float``
values are rounded down to whole seconds.
- A string specifying the time in a format supported by `Pandas'
Timedelta constructor <https://pandas.pydata.org/docs/reference/api/pandas.Timedelta.html>`_,
e.g. ``"2 minute"``, ``"20s"``, or ``"1m14s"``.
- A ``timedelta`` object from `Python's built-in datetime library
<https://docs.python.org/3/library/datetime.html#timedelta-objects>`_,
e.g. ``timedelta(seconds=70)``.
subtitles : str, bytes, Path, io.BytesIO, or dict
Optional subtitle data for the video, supporting several input types:
- ``None`` (default): No subtitles.
- A string, bytes, or Path: File path to a subtitle file in
``.vtt`` or ``.srt`` formats, or the raw content of subtitles
conforming to these formats. Paths can be absolute or relative to
the working directory (where you execute ``streamlit run``).
If providing raw content, the string must adhere to the WebVTT or
SRT format specifications.
- io.BytesIO: A BytesIO stream that contains valid ``.vtt`` or ``.srt``
formatted subtitle data.
- A dictionary: Pairs of labels and file paths or raw subtitle content in
``.vtt`` or ``.srt`` formats to enable multiple subtitle tracks.
The label will be shown in the video player. Example:
``{"English": "path/to/english.vtt", "French": "path/to/french.srt"}``
When provided, subtitles are displayed by default. For multiple
tracks, the first one is displayed by default. If you don't want any
subtitles displayed by default, use an empty string for the value
in a dictrionary's first pair: ``{"None": "", "English": "path/to/english.vtt"}``
Not supported for YouTube videos.
end_time : int, float, timedelta, str, or None
The time at which the element should stop playing. This can be
one of the following:
- ``None`` (default): The element plays through to the end.
- An ``int`` or ``float`` specifying the time in seconds. ``float``
values are rounded down to whole seconds.
- A string specifying the time in a format supported by `Pandas'
Timedelta constructor <https://pandas.pydata.org/docs/reference/api/pandas.Timedelta.html>`_,
e.g. ``"2 minute"``, ``"20s"``, or ``"1m14s"``.
- A ``timedelta`` object from `Python's built-in datetime library
<https://docs.python.org/3/library/datetime.html#timedelta-objects>`_,
e.g. ``timedelta(seconds=70)``.
loop : bool
Whether the video should loop playback.
autoplay : bool
Whether the video should start playing automatically. This is
``False`` by default. Browsers will not autoplay unmuted videos
if the user has not interacted with the page by clicking somewhere.
To enable autoplay without user interaction, you must also set
``muted=True``.
muted : bool
Whether the video should play with the audio silenced. This is
``False`` by default. Use this in conjunction with ``autoplay=True``
to enable autoplay without user interaction.
width : "stretch" or int
The width of the video player element. This can be one of the
following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
Example
-------
>>> import streamlit as st
>>>
>>> video_file = open("myvideo.mp4", "rb")
>>> video_bytes = video_file.read()
>>>
>>> st.video(video_bytes)
.. output::
https://doc-video.streamlit.app/
height: 700px
When you include subtitles, they will be turned on by default. A viewer
can turn off the subtitles (or captions) from the browser's default video
control menu, usually located in the lower-right corner of the video.
Here is a simple VTT file (``subtitles.vtt``):
>>> WEBVTT
>>>
>>> 0:00:01.000 --> 0:00:02.000
>>> Look!
>>>
>>> 0:00:03.000 --> 0:00:05.000
>>> Look at the pretty stars!
If the above VTT file lives in the same directory as your app, you can
add subtitles like so:
>>> import streamlit as st
>>>
>>> VIDEO_URL = "https://example.com/not-youtube.mp4"
>>> st.video(VIDEO_URL, subtitles="subtitles.vtt")
.. output::
https://doc-video-subtitles.streamlit.app/
height: 700px
See additional examples of supported subtitle input types in our
`video subtitles feature demo <https://doc-video-subtitle-inputs.streamlit.app/>`_.
.. note::
Some videos may not display if they are encoded using MP4V (which is an export option in OpenCV),
as this codec is not widely supported by browsers. Converting your video to H.264 will allow
the video to be displayed in Streamlit.
See this `StackOverflow post <https://stackoverflow.com/a/49535220/2394542>`_ or this
`Streamlit forum post <https://discuss.streamlit.io/t/st-video-doesnt-show-opencv-generated-mp4/3193/2>`_
for more information.
"""
start_time, end_time = _parse_start_time_end_time(start_time, end_time)
validate_width(width)
video_proto = VideoProto()
coordinates = self.dg._get_delta_path_str()
marshall_video(
self.dg,
coordinates,
video_proto,
data,
format,
start_time,
subtitles,
end_time,
loop,
autoplay,
muted,
width=width,
)
return self.dg._enqueue("video", video_proto)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
# Regular expression from
# https://gist.github.com/rodrigoborgesdeoliveira/987683cfbfcc8d800192da1e73adc486?permalink_comment_id=4645864#gistcomment-4645864
# Covers any youtube URL (incl. shortlinks and embed links) and extracts its video code.
YOUTUBE_RE: Final = r"^((https?://(?:www\.)?(?:m\.)?youtube\.com))/((?:oembed\?url=https?%3A//(?:www\.)youtube.com/watch\?(?:v%3D)(?P<video_id_1>[\w\-]{10,20})&format=json)|(?:attribution_link\?a=.*watch(?:%3Fv%3D|%3Fv%3D)(?P<video_id_2>[\w\-]{10,20}))(?:%26feature.*))|(https?:)?(\/\/)?((www\.|m\.)?youtube(-nocookie)?\.com\/((watch)?\?(app=desktop&)?(feature=\w*&)?v=|embed\/|v\/|e\/)|youtu\.be\/)(?P<video_id_3>[\w\-]{10,20})"
def _reshape_youtube_url(url: str) -> str | None:
"""Return whether URL is any kind of YouTube embed or watch link. If so,
reshape URL into an embed link suitable for use in an iframe.
If not a YouTube URL, return None.
Parameters
----------
url : str
Example
-------
>>> print(_reshape_youtube_url("https://youtu.be/_T8LGqJtuGc"))
.. output::
https://www.youtube.com/embed/_T8LGqJtuGc
"""
match = re.match(YOUTUBE_RE, url)
if match:
code = (
match.group("video_id_1")
or match.group("video_id_2")
or match.group("video_id_3")
)
return f"https://www.youtube.com/embed/{code}"
return None
def _marshall_av_media(
coordinates: str,
proto: AudioProto | VideoProto,
data: MediaData,
mimetype: str,
) -> None:
"""Fill audio or video proto based on contents of data.
Given a string, check if it's a url; if so, send it out without modification.
Otherwise assume strings are filenames and let any OS errors raise.
Load data either from file or through bytes-processing methods into a
MediaFile object. Pack proto with generated Tornado-based URL.
(When running in "raw" mode, we won't actually load data into the
MediaFileManager, and we'll return an empty URL.)
"""
# Audio and Video methods have already checked if this is a URL by this point.
if data is None:
# Allow empty values so media players can be shown without media.
return
data_or_filename: bytes | str
if isinstance(data, (str, bytes)):
# Pass strings and bytes through unchanged
data_or_filename = data
elif isinstance(data, Path):
data_or_filename = str(data)
elif isinstance(data, io.BytesIO):
data.seek(0)
data_or_filename = data.getvalue()
elif isinstance(data, (io.RawIOBase, io.BufferedReader)):
data.seek(0)
read_data = data.read()
if read_data is None:
return
data_or_filename = read_data
elif type_util.is_type(data, "numpy.ndarray"):
data_or_filename = data.tobytes()
else:
raise RuntimeError(f"Invalid binary data format: {type(data)}")
if runtime.exists():
file_url = runtime.get_instance().media_file_mgr.add(
data_or_filename, mimetype, coordinates
)
caching.save_media_data(data_or_filename, mimetype, coordinates)
else:
# When running in "raw mode", we can't access the MediaFileManager.
file_url = ""
proto.url = file_url
def marshall_video(
dg: DeltaGenerator,
coordinates: str,
proto: VideoProto,
data: MediaData,
mimetype: str = "video/mp4",
start_time: int = 0,
subtitles: SubtitleData = None,
end_time: int | None = None,
loop: bool = False,
autoplay: bool = False,
muted: bool = False,
width: WidthWithoutContent = "stretch",
) -> None:
"""Marshalls a video proto, using url processors as needed.
Parameters
----------
coordinates : str
proto : the proto to fill. Must have a string field called "data".
data : str, Path, bytes, BytesIO, numpy.ndarray, or file opened with
io.open().
Raw video data or a string with a URL pointing to the video
to load. Includes support for YouTube URLs.
If passing the raw data, this must include headers and any other
bytes required in the actual file.
mimetype : str
The mime type for the video file. Defaults to 'video/mp4'.
See https://tools.ietf.org/html/rfc4281 for more info.
start_time : int
The time from which this element should start playing. (default: 0)
subtitles: str, dict, or io.BytesIO
Optional subtitle data for the video, supporting several input types:
- None (default): No subtitles.
- A string: File path to a subtitle file in '.vtt' or '.srt' formats, or the raw content
of subtitles conforming to these formats. If providing raw content, the string must
adhere to the WebVTT or SRT format specifications.
- A dictionary: Pairs of labels and file paths or raw subtitle content in '.vtt' or '.srt' formats.
Enables multiple subtitle tracks. The label will be shown in the video player.
Example: {'English': 'path/to/english.vtt', 'French': 'path/to/french.srt'}
- io.BytesIO: A BytesIO stream that contains valid '.vtt' or '.srt' formatted subtitle data.
When provided, subtitles are displayed by default. For multiple tracks, the first one is displayed by default.
Not supported for YouTube videos.
end_time: int
The time at which this element should stop playing
loop: bool
Whether the video should loop playback.
autoplay: bool
Whether the video should start playing automatically.
Browsers will not autoplay video files if the user has not interacted with
the page yet, for example by clicking on the page while it loads.
To enable autoplay without user interaction, you can set muted=True.
Defaults to False.
muted: bool
Whether the video should play with the audio silenced. This can be used to
enable autoplay without user interaction. Defaults to False.
width: int or "stretch"
The width of the video player. This can be one of the following:
- An int: The width in pixels, e.g. 200 for a width of 200 pixels.
- "stretch": The default value. The video player stretches to fill
available space in its container.
"""
if start_time < 0 or (end_time is not None and end_time <= start_time):
raise StreamlitAPIException("Invalid start_time and end_time combination.")
proto.start_time = start_time
proto.muted = muted
if end_time is not None:
proto.end_time = end_time
proto.loop = loop
width_config = WidthConfig()
if isinstance(width, int):
width_config.pixel_width = width
else:
width_config.use_stretch = True
proto.width_config.CopyFrom(width_config)
# "type" distinguishes between YouTube and non-YouTube links
proto.type = VideoProto.Type.NATIVE
if isinstance(data, Path):
data = str(data) # Convert Path to string
if isinstance(data, str) and url_util.is_url(
data, allowed_schemas=("http", "https", "data")
):
if youtube_url := _reshape_youtube_url(data):
proto.url = youtube_url
proto.type = VideoProto.Type.YOUTUBE_IFRAME
if subtitles:
raise StreamlitAPIException(
"Subtitles are not supported for YouTube videos."
)
else:
proto.url = data
else:
_marshall_av_media(coordinates, proto, data, mimetype)
if subtitles:
subtitle_items: list[tuple[str, str | Path | bytes | io.BytesIO]] = []
# Single subtitle
if isinstance(subtitles, (str, bytes, io.BytesIO, Path)):
subtitle_items.append(("default", subtitles))
# Multiple subtitles
elif isinstance(subtitles, dict):
subtitle_items.extend(subtitles.items())
else:
raise StreamlitAPIException(
f"Unsupported data type for subtitles: {type(subtitles)}. "
f"Only str (file paths) and dict are supported."
)
for label, subtitle_data in subtitle_items:
sub = proto.subtitles.add()
sub.label = label or ""
# Coordinates used in media_file_manager to identify the place of
# element, in case of subtitle, we use same video coordinates
# with suffix.
# It is not aligned with common coordinates format, but in
# media_file_manager we use it just as unique identifier, so it is fine.
subtitle_coordinates = f"{coordinates}[subtitle{label}]"
try:
sub.url = process_subtitle_data(
subtitle_coordinates, subtitle_data, label
)
except (TypeError, ValueError) as original_err:
raise StreamlitAPIException(
f"Failed to process the provided subtitle: {label}"
) from original_err
if autoplay:
proto.autoplay = autoplay
proto.id = compute_and_register_element_id(
"video",
# video does not yet allow setting a user-defined key
user_key=None,
key_as_main_identity=False,
dg=dg,
url=proto.url,
mimetype=mimetype,
start_time=start_time,
end_time=end_time,
loop=loop,
autoplay=autoplay,
muted=muted,
width=width,
)
def _parse_start_time_end_time(
start_time: MediaTime, end_time: MediaTime | None
) -> tuple[int, int | None]:
"""Parse start_time and end_time and return them as int."""
try:
maybe_start_time = time_to_seconds(start_time, coerce_none_to_inf=False)
if maybe_start_time is None:
raise ValueError # noqa: TRY301
start_time = int(maybe_start_time)
except (StreamlitAPIException, ValueError):
error_msg = TIMEDELTA_PARSE_ERROR_MESSAGE.format(
param_name="start_time", param_value=start_time
)
raise StreamlitAPIException(error_msg) from None
try:
end_time = time_to_seconds(end_time, coerce_none_to_inf=False)
if end_time is not None:
end_time = int(end_time)
except StreamlitAPIException:
error_msg = TIMEDELTA_PARSE_ERROR_MESSAGE.format(
param_name="end_time", param_value=end_time
)
raise StreamlitAPIException(error_msg) from None
return start_time, end_time
def _validate_and_normalize(data: npt.NDArray[Any]) -> tuple[bytes, int]:
"""Validates and normalizes numpy array data.
We validate numpy array shape (should be 1d or 2d)
We normalize input data to int16 [-32768, 32767] range.
Parameters
----------
data : numpy array
numpy array to be validated and normalized
Returns
-------
Tuple of (bytes, int)
(bytes, nchan)
where
- bytes : bytes of normalized numpy array converted to int16
- nchan : number of channels for audio signal. 1 for mono, or 2 for stereo.
"""
# we import numpy here locally to import it only when needed (when numpy array given
# to st.audio data)
import numpy as np
transformed_data: npt.NDArray[Any] = np.array(data, dtype=float)
if len(transformed_data.shape) == 1:
nchan = 1
elif len(transformed_data.shape) == 2:
# In wave files,channels are interleaved. E.g.,
# "L1R1L2R2..." for stereo. See
# http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx
# for channel ordering
nchan = transformed_data.shape[0]
transformed_data = transformed_data.T.ravel()
else:
raise StreamlitAPIException("Numpy array audio input must be a 1D or 2D array.")
if transformed_data.size == 0:
return transformed_data.astype(np.int16).tobytes(), nchan
max_abs_value: npt.NDArray[Any] = np.max(np.abs(transformed_data))
# 16-bit samples are stored as 2's-complement signed integers,
# ranging from -32768 to 32767.
# scaled_data is PCM 16 bit numpy array, that's why we multiply [-1, 1] float
# values to 32_767 == 2 ** 15 - 1.
np_array = (transformed_data / max_abs_value) * 32767
scaled_data = np_array.astype(np.int16)
return scaled_data.tobytes(), nchan
def _make_wav(data: npt.NDArray[Any], sample_rate: int) -> bytes:
"""
Transform a numpy array to a PCM bytestring.
We use code from IPython display module to convert numpy array to wave bytes
https://github.com/ipython/ipython/blob/1015c392f3d50cf4ff3e9f29beede8c1abfdcb2a/IPython/lib/display.py#L146
"""
# we import wave here locally to import it only when needed (when numpy array given
# to st.audio data)
import wave
scaled, nchan = _validate_and_normalize(data)
with io.BytesIO() as fp, wave.open(fp, mode="wb") as waveobj:
waveobj.setnchannels(nchan)
waveobj.setframerate(sample_rate)
waveobj.setsampwidth(2)
waveobj.setcomptype("NONE", "NONE")
waveobj.writeframes(scaled)
return fp.getvalue()
def _maybe_convert_to_wav_bytes(data: MediaData, sample_rate: int | None) -> MediaData:
"""Convert data to wav bytes if the data type is numpy array."""
if type_util.is_type(data, "numpy.ndarray") and sample_rate is not None:
data = _make_wav(cast("npt.NDArray[Any]", data), sample_rate)
return data
def marshall_audio(
dg: DeltaGenerator,
coordinates: str,
proto: AudioProto,
data: MediaData,
mimetype: str = "audio/wav",
start_time: int = 0,
sample_rate: int | None = None,
end_time: int | None = None,
loop: bool = False,
autoplay: bool = False,
width: WidthWithoutContent = "stretch",
) -> None:
"""Marshalls an audio proto, using data and url processors as needed.
Parameters
----------
coordinates : str
proto : The proto to fill. Must have a string field called "url".
data : str, Path, bytes, BytesIO, numpy.ndarray, or file opened with
io.open()
Raw audio data or a string with a URL pointing to the file to load.
If passing the raw data, this must include headers and any other bytes
required in the actual file.
mimetype : str
The mime type for the audio file. Defaults to "audio/wav".
See https://tools.ietf.org/html/rfc4281 for more info.
start_time : int
The time from which this element should start playing. (default: 0)
sample_rate: int or None
Optional param to provide sample_rate in case of numpy array
end_time: int
The time at which this element should stop playing
loop: bool
Whether the audio should loop playback.
autoplay : bool
Whether the audio should start playing automatically.
Browsers will not autoplay audio files if the user has not interacted with the page yet.
width: int or "stretch"
The width of the audio player. This can be one of the following:
- An int: The width in pixels, e.g. 200 for a width of 200 pixels.
- "stretch": The default value. The audio player stretches to fill
available space in its container.
"""
proto.start_time = start_time
if end_time is not None:
proto.end_time = end_time
proto.loop = loop
width_config = WidthConfig()
if isinstance(width, int):
width_config.pixel_width = width
else:
width_config.use_stretch = True
proto.width_config.CopyFrom(width_config)
if isinstance(data, Path):
data = str(data) # Convert Path to string
if isinstance(data, str) and url_util.is_url(
data, allowed_schemas=("http", "https", "data")
):
proto.url = data
else:
data = _maybe_convert_to_wav_bytes(data, sample_rate)
_marshall_av_media(coordinates, proto, data, mimetype)
if autoplay:
proto.autoplay = autoplay
proto.id = compute_and_register_element_id(
"audio",
user_key=None,
key_as_main_identity=False,
dg=dg,
url=proto.url,
mimetype=mimetype,
start_time=start_time,
sample_rate=sample_rate,
end_time=end_time,
loop=loop,
autoplay=autoplay,
width=width,
)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/progress.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import math
from typing import TYPE_CHECKING, TypeAlias, cast
from streamlit.elements.lib.layout_utils import LayoutConfig, validate_width
from streamlit.errors import StreamlitAPIException
from streamlit.proto.Progress_pb2 import Progress as ProgressProto
from streamlit.string_util import clean_text
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
from streamlit.elements.lib.layout_utils import WidthWithoutContent
# Currently, equates to just float, but we can't use `numbers.Real` due to
# https://github.com/python/mypy/issues/3186
FloatOrInt: TypeAlias = int | float
def _check_float_between(value: float, low: float = 0.0, high: float = 1.0) -> bool:
"""
Checks given value is 'between' the bounds of [low, high],
considering close values around bounds are acceptable input.
Notes
-----
This check is required for handling values that are slightly above or below the
acceptable range, for example -0.0000000000021, 1.0000000000000013.
These values are little off the conventional 0.0 <= x <= 1.0 condition
due to floating point operations, but should still be considered acceptable input.
Parameters
----------
value : float
low : float
high : float
"""
return (
(low <= value <= high)
or math.isclose(value, low, rel_tol=1e-9, abs_tol=1e-9)
or math.isclose(value, high, rel_tol=1e-9, abs_tol=1e-9)
)
def _get_value(value: FloatOrInt) -> int:
if isinstance(value, int):
if 0 <= value <= 100:
return value
raise StreamlitAPIException(
f"Progress Value has invalid value [0, 100]: {value}"
)
if isinstance(value, float):
if _check_float_between(value, low=0.0, high=1.0):
return int(value * 100)
raise StreamlitAPIException(
f"Progress Value has invalid value [0.0, 1.0]: {value}"
)
raise StreamlitAPIException(
f"Progress Value has invalid type: {type(value).__name__}"
)
def _get_text(text: str | None) -> str | None:
if text is None:
return None
if isinstance(text, str):
return clean_text(text)
raise StreamlitAPIException(
f"Progress Text is of type {type(text)}, which is not an accepted type."
"Text only accepts: str. Please convert the text to an accepted type."
)
class ProgressMixin:
def progress(
self,
value: FloatOrInt,
text: str | None = None,
width: WidthWithoutContent = "stretch",
) -> DeltaGenerator:
r"""Display a progress bar.
Parameters
----------
value : int or float
0 <= value <= 100 for int
0.0 <= value <= 1.0 for float
text : str or None
A message to display above the progress bar. The text can optionally
contain GitHub-flavored Markdown of the following types: Bold, Italics,
Strikethroughs, Inline Code, Links, and Images. Images display like
icons, with a max height equal to the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
width : "stretch" or int
The width of the progress element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
Example
-------
Here is an example of a progress bar increasing over time and disappearing when it reaches completion:
>>> import streamlit as st
>>> import time
>>>
>>> progress_text = "Operation in progress. Please wait."
>>> my_bar = st.progress(0, text=progress_text)
>>>
>>> for percent_complete in range(100):
... time.sleep(0.01)
... my_bar.progress(percent_complete + 1, text=progress_text)
>>> time.sleep(1)
>>> my_bar.empty()
>>>
>>> st.button("Rerun")
.. output::
https://doc-status-progress.streamlit.app/
height: 220px
"""
# TODO: standardize numerical type checking across st.* functions.
progress_proto = ProgressProto()
progress_proto.value = _get_value(value)
text = _get_text(text)
if text is not None:
progress_proto.text = text
validate_width(width)
layout_config = LayoutConfig(width=width)
return self.dg._enqueue("progress", progress_proto, layout_config=layout_config)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/snow.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from typing import TYPE_CHECKING, cast
from streamlit.proto.Snow_pb2 import Snow as SnowProto
from streamlit.runtime.metrics_util import gather_metrics
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
class SnowMixin:
@gather_metrics("snow")
def snow(self) -> DeltaGenerator:
"""Draw celebratory snowfall.
Example
-------
>>> import streamlit as st
>>>
>>> st.snow()
...then watch your app and get ready for a cool celebration!
"""
snow_proto = SnowProto()
snow_proto.show = True
return self.dg._enqueue("snow", snow_proto)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/json.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import json
import types
from collections import ChainMap, UserDict
from typing import TYPE_CHECKING, Any, cast
from streamlit.elements.lib.layout_utils import (
LayoutConfig,
WidthWithoutContent,
validate_width,
)
from streamlit.proto.Json_pb2 import Json as JsonProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.type_util import (
is_custom_dict,
is_list_like,
is_namedtuple,
is_pydantic_model,
)
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
def _ensure_serialization(o: object) -> str | list[Any]:
"""A repr function for json.dumps default arg, which tries to serialize sets
as lists.
"""
return list(o) if isinstance(o, set) else repr(o)
class JsonMixin:
@gather_metrics("json")
def json(
self,
body: object,
*, # keyword-only arguments:
expanded: bool | int = True,
width: WidthWithoutContent = "stretch",
) -> DeltaGenerator:
"""Display an object or string as a pretty-printed, interactive JSON string.
Parameters
----------
body : object or str
The object to print as JSON. All referenced objects should be
serializable to JSON as well. If object is a string, we assume it
contains serialized JSON.
expanded : bool or int
The initial expansion state of the JSON element. This can be one
of the following:
- ``True`` (default): The element is fully expanded.
- ``False``: The element is fully collapsed.
- An integer: The element is expanded to the depth specified. The
integer must be non-negative. ``expanded=0`` is equivalent to
``expanded=False``.
Regardless of the initial expansion state, users can collapse or
expand any key-value pair to show or hide any part of the object.
width : "stretch" or int
The width of the JSON element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
Example
-------
>>> import streamlit as st
>>>
>>> st.json(
... {
... "foo": "bar",
... "stuff": [
... "stuff 1",
... "stuff 2",
... "stuff 3",
... ],
... "level1": {"level2": {"level3": {"a": "b"}}},
... },
... expanded=2,
... )
.. output::
https://doc-json.streamlit.app/
height: 385px
"""
if is_custom_dict(body):
body = body.to_dict() # ty: ignore[unresolved-attribute]
if is_namedtuple(body):
body = body._asdict() # ty: ignore[unresolved-attribute]
if isinstance(
body, (ChainMap, types.MappingProxyType, UserDict)
) or is_pydantic_model(body):
body = dict(body) # type: ignore
if is_list_like(body):
body = list(body) # ty: ignore[invalid-argument-type]
if not isinstance(body, str):
try:
# Serialize body to string and try to interpret sets as lists
body = json.dumps(body, default=_ensure_serialization)
except TypeError as err:
self.dg.warning(
"Warning: this data structure was not fully serializable as "
f"JSON due to one or more unexpected keys. (Error was: {err})"
)
body = json.dumps(body, skipkeys=True, default=_ensure_serialization)
json_proto = JsonProto()
json_proto.body = body
if isinstance(expanded, bool):
json_proto.expanded = expanded
elif isinstance(expanded, int):
json_proto.expanded = True
json_proto.max_expand_depth = expanded
else:
raise TypeError(
f"The type {type(expanded)} of `expanded` is not supported"
", must be bool or int."
)
validate_width(width)
layout_config = LayoutConfig(width=width)
return self.dg._enqueue("json", json_proto, layout_config=layout_config)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/vega_charts.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
"""Collection of chart commands that are rendered via our vega-lite chart component."""
from __future__ import annotations
import json
import re
import threading
from contextlib import nullcontext
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
Any,
Final,
Literal,
TypeAlias,
TypedDict,
Union,
cast,
overload,
)
from typing_extensions import Required
from streamlit import dataframe_util, type_util
from streamlit.deprecation_util import (
make_deprecated_name_warning,
show_deprecation_warning,
)
from streamlit.elements.lib import dicttools
from streamlit.elements.lib.built_in_chart_utils import (
AddRowsMetadata,
ChartStackType,
ChartType,
generate_chart,
maybe_raise_stack_warning,
)
from streamlit.elements.lib.form_utils import current_form_id
from streamlit.elements.lib.layout_utils import (
Height,
LayoutConfig,
Width,
validate_height,
validate_width,
)
from streamlit.elements.lib.policies import check_widget_policies
from streamlit.elements.lib.utils import Key, compute_and_register_element_id, to_key
from streamlit.errors import StreamlitAPIException
from streamlit.proto.ArrowVegaLiteChart_pb2 import (
ArrowVegaLiteChart as ArrowVegaLiteChartProto,
)
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner_utils.script_run_context import get_script_run_ctx
from streamlit.runtime.state import WidgetCallback, register_widget
from streamlit.util import AttributeDictionary, calc_md5
if TYPE_CHECKING:
from collections.abc import Iterable, Sequence
import altair as alt
from streamlit.dataframe_util import Data
from streamlit.delta_generator import DeltaGenerator
from streamlit.elements.lib.color_util import Color
# See https://vega.github.io/vega-lite/docs/encoding.html
_CHANNELS: Final = {
"x",
"y",
"x2",
"y2",
"xError",
"xError2",
"yError",
"yError2",
"longitude",
"latitude",
"color",
"opacity",
"fillOpacity",
"strokeOpacity",
"strokeWidth",
"size",
"shape",
"text",
"tooltip",
"href",
"key",
"order",
"detail",
"facet",
"row",
"column",
}
VegaLiteSpec: TypeAlias = dict[str, Any]
AltairChart: TypeAlias = Union[
"alt.Chart",
"alt.ConcatChart",
"alt.FacetChart",
"alt.HConcatChart",
"alt.LayerChart",
"alt.RepeatChart",
"alt.VConcatChart",
]
_altair_globals_lock = threading.Lock()
class VegaLiteState(TypedDict, total=False):
"""
The schema for the Vega-Lite event state.
The event state is stored in a dictionary-like object that supports both
key and attribute notation. Event states cannot be programmatically
changed or set through Session State.
Only selection events are supported at this time.
Attributes
----------
selection : dict
The state of the ``on_select`` event. This attribute returns a
dictionary-like object that supports both key and attribute notation.
The name of each Vega-Lite selection parameter becomes an attribute in
the ``selection`` dictionary. The format of the data within each
attribute is determined by the selection parameter definition within
Vega-Lite.
Examples
--------
The following two examples have equivalent definitions. Each one has a
point and interval selection parameter include in the chart definition.
The point selection parameter is named ``"point_selection"``. The interval
or box selection parameter is named ``"interval_selection"``.
**Example 1: Chart selections with ``st.altair_chart``**
>>> import altair as alt
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(rng(0).standard_normal((20, 3)), columns=["a", "b", "c"])
>>>
>>> point_selector = alt.selection_point("point_selection")
>>> interval_selector = alt.selection_interval("interval_selection")
>>> chart = (
... alt.Chart(df)
... .mark_circle()
... .encode(
... x="a",
... y="b",
... size="c",
... color="c",
... tooltip=["a", "b", "c"],
... fillOpacity=alt.condition(point_selector, alt.value(1), alt.value(0.3)),
... )
... .add_params(point_selector, interval_selector)
... )
>>>
>>> event = st.altair_chart(chart, key="alt_chart", on_select="rerun")
>>>
>>> event
**Example 2: Chart selections with ``st.vega_lite_chart``**
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(rng(0).standard_normal((20, 3)), columns=["a", "b", "c"])
>>>
>>> spec = {
... "mark": {"type": "circle", "tooltip": True},
... "params": [
... {"name": "interval_selection", "select": "interval"},
... {"name": "point_selection", "select": "point"},
... ],
... "encoding": {
... "x": {"field": "a", "type": "quantitative"},
... "y": {"field": "b", "type": "quantitative"},
... "size": {"field": "c", "type": "quantitative"},
... "color": {"field": "c", "type": "quantitative"},
... "fillOpacity": {
... "condition": {"param": "point_selection", "value": 1},
... "value": 0.3,
... },
... },
... }
>>>
>>> event = st.vega_lite_chart(df, spec, key="vega_chart", on_select="rerun")
>>>
>>> event
Try selecting points in this interactive example. When you click a point,
the selection will appear under the attribute, ``"point_selection"``, which
is the name given to the point selection parameter. Similarly, when you
make an interval selection, it will appear under the attribute
``"interval_selection"``. You can give your selection parameters other
names if desired.
If you hold ``Shift`` while selecting points, existing point selections
will be preserved. Interval selections are not preserved when making
additional selections.
.. output::
https://doc-chart-events-vega-lite-state.streamlit.app
height: 600px
"""
selection: Required[AttributeDictionary]
@dataclass
class VegaLiteStateSerde:
"""VegaLiteStateSerde is used to serialize and deserialize the VegaLite Chart state."""
selection_parameters: Sequence[str]
def deserialize(self, ui_value: str | None) -> VegaLiteState:
empty_selection_state: VegaLiteState = {
"selection": AttributeDictionary(
# Initialize the select state with empty dictionaries for each selection parameter.
{param: {} for param in self.selection_parameters}
),
}
selection_state = (
empty_selection_state
if ui_value is None
else cast("VegaLiteState", AttributeDictionary(json.loads(ui_value)))
)
if "selection" not in selection_state:
selection_state = empty_selection_state # type: ignore[unreachable]
return cast("VegaLiteState", AttributeDictionary(selection_state))
def serialize(self, selection_state: VegaLiteState) -> str:
return json.dumps(selection_state, default=str)
def _patch_null_legend_titles(spec: VegaLiteSpec) -> None:
"""Patches null legend titles in the 'color' channel of the spec.
This is a fix for the Vega-Lite bug where null legend titles
cause a wrong formatting of the chart as shown on the issue #9339.
"""
encoding = spec.get("encoding")
if not isinstance(encoding, dict):
return
color_spec = encoding.get("color")
if not isinstance(color_spec, dict):
return
if "title" in color_spec and color_spec.get("title") is None:
# Patch legend title given null value directly in the encoding
color_spec["title"] = " "
legend = color_spec.get("legend")
if isinstance(legend, dict) and "title" in legend and legend.get("title") is None:
# Patch legend title given null value in the legend
legend["title"] = " "
def _prepare_vega_lite_spec(
spec: VegaLiteSpec,
use_container_width: bool,
**kwargs: Any,
) -> VegaLiteSpec:
if kwargs:
# Support passing in kwargs.
# > marshall(proto, {foo: 'bar'}, baz='boz')
# Merge spec with unflattened kwargs, where kwargs take precedence.
# This only works for string keys, but kwarg keys are strings anyways.
spec = dict(spec, **dicttools.unflatten(kwargs, _CHANNELS))
else:
# Clone the spec dict, since we may be mutating it.
spec = dict(spec)
if len(spec) == 0:
raise StreamlitAPIException("Vega-Lite charts require a non-empty spec dict.")
if "autosize" not in spec:
# type fit does not work for many chart types. This change focuses
# on vconcat with use_container_width=True as there are unintended
# consequences of changing the default autosize for all charts.
# fit-x fits the width and height can be adjusted.
is_facet_chart = "facet" in spec or (
"encoding" in spec
and (any(x in spec["encoding"] for x in ["row", "column", "facet"]))
)
if "vconcat" in spec and use_container_width:
spec["autosize"] = {"type": "fit-x", "contains": "padding"}
elif is_facet_chart:
spec["autosize"] = {"type": "pad", "contains": "padding"}
else:
spec["autosize"] = {"type": "fit", "contains": "padding"}
_patch_null_legend_titles(spec)
return spec
def _marshall_chart_data(
proto: ArrowVegaLiteChartProto,
spec: VegaLiteSpec,
data: Data = None,
) -> None:
"""Adds the data to the proto and removes it from the spec dict.
These operations will happen in-place.
"""
# Pull data out of spec dict when it's in a 'datasets' key:
# datasets: {foo: df1_bytes, bar: df2_bytes}, ...}
if "datasets" in spec:
for dataset_name, dataset_data in spec["datasets"].items():
dataset = proto.datasets.add()
dataset.name = str(dataset_name)
dataset.has_name = True
# The ID transformer (_to_arrow_dataset function registered before conversion to dict)
# already serializes the data into Arrow IPC format (bytes) when the Altair object
# gets converted into the vega-lite spec dict.
# If its already in bytes, we don't need to serialize it here again.
# We just need to pass the data information into the correct proto fields.
# TODO(lukasmasuch): Are there any other cases where we need to serialize the data
# or can we remove the convert_anything_to_arrow_bytes here?
dataset.data.data = (
dataset_data
if isinstance(dataset_data, bytes)
else dataframe_util.convert_anything_to_arrow_bytes(dataset_data)
)
del spec["datasets"]
# Pull data out of spec dict when it's in a top-level 'data' key:
# > {data: df}
# > {data: {values: df, ...}}
# > {data: {url: 'url'}}
# > {data: {name: 'foo'}}
if "data" in spec:
data_spec = spec["data"]
if isinstance(data_spec, dict):
if "values" in data_spec:
data = data_spec["values"]
del spec["data"]
else:
data = data_spec
del spec["data"]
if data is not None:
proto.data.data = dataframe_util.convert_anything_to_arrow_bytes(data)
def _convert_altair_to_vega_lite_spec(
altair_chart: AltairChart,
) -> VegaLiteSpec:
"""Convert an Altair chart object to a Vega-Lite chart spec."""
import altair as alt
# alt.themes was deprecated in Altair 5.5.0 in favor of alt.theme
if type_util.is_altair_version_less_than("5.5.0"):
alt_theme = alt.themes # ty: ignore[unresolved-attribute]
else:
alt_theme = alt.theme
# This is where we'll store Arrow-serialized versions of the chart data.
# This happens in _to_arrow_dataset().
datasets: dict[str, Any] = {}
# Normally altair_chart.to_dict() would transform the dataframe used by the
# chart into an array of dictionaries. To avoid that, we install a
# transformer that replaces datasets with a reference by the object id of
# the dataframe. We then fill in the dataset manually later on.
#
# Note: it's OK to re-register this every time we run this function since
# transformers are stored in a dict. So there's no duplication.
#
# type: ignore[arg-type,attr-defined,unused-ignore]
alt.data_transformers.register("to_arrow_dataset", _to_arrow_dataset)
# Settings like alt.theme.enable and alt.data_transformers.enable are global to all
# threads. So this lock makes sure that whatever we set those to only apply to the
# current thread.
with _altair_globals_lock:
# The default altair theme has some width/height defaults defined
# which are not useful for Streamlit. Therefore, we change the theme to
# "none" to avoid those defaults.
theme_context = (
alt_theme.enable("none") if alt_theme.active == "default" else nullcontext()
)
data_transformer = alt.data_transformers.enable(
"to_arrow_dataset", datasets=datasets
)
with theme_context: # ty: ignore[invalid-context-manager]
# type: ignore[attr-defined,unused-ignore]
with data_transformer: # ty: ignore[invalid-context-manager]
chart_dict = altair_chart.to_dict()
# Put datasets back into the chart dict:
chart_dict["datasets"] = datasets
return chart_dict
def _disallow_multi_view_charts(spec: VegaLiteSpec) -> None:
"""Raise an exception if the spec contains a multi-view chart (view composition).
This is intended to be used as a temporary solution to prevent selections on
multi-view charts. There are too many edge cases to handle selections on these
charts correctly, so we're disallowing them for now.
More information about view compositions: https://vega.github.io/vega-lite/docs/composition.html
"""
if (
any(key in spec for key in ["layer", "hconcat", "vconcat", "concat", "spec"])
or "encoding" not in spec
):
raise StreamlitAPIException(
"Selections are not yet supported for multi-view charts (chart compositions). "
"If you would like to use selections on multi-view charts, please upvote "
"this [Github issue](https://github.com/streamlit/streamlit/issues/8643)."
)
def _extract_selection_parameters(spec: VegaLiteSpec) -> set[str]:
"""Extract the names of all valid selection parameters from the spec."""
if not spec or "params" not in spec:
return set()
param_names = set()
for param in spec["params"]:
# Check if it looks like a valid selection parameter:
# https://vega.github.io/vega-lite/docs/selection.html
if param.get("name") and param.get("select"):
# Selection found, just return here to not show the exception.
param_names.add(param["name"])
return param_names
def _parse_selection_mode(
spec: VegaLiteSpec,
selection_mode: str | Iterable[str] | None,
) -> list[str]:
"""Parse and check the user provided selection modes.
This will raise an exception if no valid selection parameters are found in the spec
or if the user provided selection modes are not defined in the spec.
Parameters
----------
spec : VegaLiteSpec
The Vega-Lite chart specification.
selection_mode : str, Iterable[str], or None
The user provided selection mode(s).
Returns
-------
list[str]
The parsed selection mode(s) that should be activated.
"""
# Extract all selection parameters from the spec:
all_selection_params = _extract_selection_parameters(spec)
if not all_selection_params:
raise StreamlitAPIException(
"Selections are activated, but the provided chart spec does not "
"have any selections defined. To add selections to `st.altair_chart`, check out the documentation "
"[here](https://altair-viz.github.io/user_guide/interactions.html#selections-capturing-chart-interactions)."
" For adding selections to `st.vega_lite_chart`, take a look "
"at the specification [here](https://vega.github.io/vega-lite/docs/selection.html)."
)
if selection_mode is None:
# Activate all selection parameters:
return sorted(all_selection_params)
if isinstance(selection_mode, str):
# Convert single string to list:
selection_mode = [selection_mode]
# Check that all provided selection parameters are defined in the spec:
for selection_name in selection_mode:
if selection_name not in all_selection_params:
raise StreamlitAPIException(
f"Selection parameter '{selection_name}' is not defined in the chart "
f"spec. Available selection parameters are: {all_selection_params}."
)
return sorted(selection_mode)
def _reset_counter_pattern(prefix: str, vega_spec: str) -> str:
"""Altair uses a global counter for unnamed parameters and views.
We need to reset these counters on a spec-level to make the
spec stable across reruns and avoid changes to the element ID.
"""
# Altair 6.0.0 introduced a new way to handle parameters,
# by using hashes instead of pure counters:
pattern = re.compile(rf'"{prefix}[0-9a-z]+"')
# Get all matches without duplicates in order of appearance.
# Using a set here would not guarantee the order of appearance,
# which might lead to different replacements on each run.
# The order of the spec from Altair is expected to stay stable
# within the same session / Altair version.
# The order might change with Altair updates, but that's not really
# a case that is relevant for us since we mainly care about having
# this stable within a session.
if matches := list(dict.fromkeys(pattern.findall(vega_spec))):
# Add a prefix to the replacement to avoid
# replacing instances that already have been replaced before.
# The prefix here is arbitrarily chosen with the main goal
# that its extremely unlikely to already be part of the spec:
replacement_prefix = "__replace_prefix_o9hd101n22e1__"
# Replace all matches with a counter starting from 1
# We start from 1 to imitate the altair behavior.
for counter, match in enumerate(matches, start=1):
vega_spec = vega_spec.replace(
match, f'"{replacement_prefix}{prefix}{counter}"'
)
# Remove the prefix again from all replacements:
vega_spec = vega_spec.replace(replacement_prefix, "")
return vega_spec
def _stabilize_vega_json_spec(vega_spec: str) -> str:
"""Makes the chart spec stay stable across reruns and sessions.
Altair auto creates names for unnamed parameters & views. It uses a global counter
for the naming which will result in a different spec on every rerun.
In Streamlit, we need the spec to be stable across reruns and sessions to prevent the chart
from getting a new identity. So we need to replace the names with counter with a stable name.
Having a stable chart spec is also important for features like forward message cache,
where we don't want to have changing messages on every rerun.
Parameter counter:
https://github.com/vega/altair/blob/f345cd9368ae2bbc98628e9245c93fa9fb582621/altair/vegalite/v5/api.py#L196
View counter:
https://github.com/vega/altair/blob/f345cd9368ae2bbc98628e9245c93fa9fb582621/altair/vegalite/v5/api.py#L2885
This is temporary solution waiting for a fix for this issue:
https://github.com/vega/altair/issues/3416
Other solutions we considered:
- working on the dict object: this would require to iterate through the object and do the
same kind of replacement; though we would need to know the structure and since we need
the spec in String-format anyways, we deemed that executing the replacement on the
String is the better alternative
- resetting the counter: the counter is incremented already when the chart object is created
(see this GitHub issue comment https://github.com/vega/altair/issues/3416#issuecomment-2098530464),
so it would be too late here to reset the counter with a thread-lock to prevent interference
between sessions
"""
# We only want to apply these replacements if it is really necessary
# since there is a risk that we replace names that where chosen by the user
# and thereby introduce unwanted side effects.
# We only need to apply the param_ fix if there are actually parameters defined
# somewhere in the spec. We can check for this by looking for the '"params"' key.
# This isn't a perfect check, but good enough to prevent unnecessary executions
# for the majority of charts.
if '"params"' in vega_spec:
vega_spec = _reset_counter_pattern("param_", vega_spec)
# Simple check if the spec contains a composite chart:
# https://vega.github.io/vega-lite/docs/composition.html
# Other charts will not contain the `view_` name,
# so its better to not replace this pattern.
if re.search(r'"(vconcat|hconcat|facet|layer|concat|repeat)"', vega_spec):
vega_spec = _reset_counter_pattern("view_", vega_spec)
return vega_spec
class VegaChartsMixin:
"""Mix-in class for all vega-related chart commands.
Altair is a python wrapper on top of the vega-lite spec. And our
built-in chart commands are just another layer on-top of Altair.
All of these chart commands will be eventually converted to a vega-lite
spec and rendered using the same vega-lite chart component.
"""
@gather_metrics("line_chart")
def line_chart(
self,
data: Data = None,
*,
x: str | None = None,
y: str | Sequence[str] | None = None,
x_label: str | None = None,
y_label: str | None = None,
color: str | Color | list[Color] | None = None,
width: Width = "stretch",
height: Height = "content",
use_container_width: bool | None = None,
) -> DeltaGenerator:
"""Display a line chart.
This is syntax-sugar around ``st.altair_chart``. The main difference
is this command uses the data's own column and indices to figure out
the chart's Altair spec. As a result this is easier to use for many
"just plot this" scenarios, while being less customizable.
Parameters
----------
data : Anything supported by st.dataframe
Data to be plotted.
x : str or None
Column name or key associated to the x-axis data. If ``x`` is
``None`` (default), Streamlit uses the data index for the x-axis
values.
y : str, Sequence of str, or None
Column name(s) or key(s) associated to the y-axis data. If this is
``None`` (default), Streamlit draws the data of all remaining
columns as data series. If this is a ``Sequence`` of strings,
Streamlit draws several series on the same chart by melting your
wide-format table into a long-format table behind the scenes.
x_label : str or None
The label for the x-axis. If this is ``None`` (default), Streamlit
will use the column name specified in ``x`` if available, or else
no label will be displayed.
y_label : str or None
The label for the y-axis. If this is ``None`` (default), Streamlit
will use the column name(s) specified in ``y`` if available, or
else no label will be displayed.
color : str, tuple, Sequence of str, Sequence of tuple, or None
The color to use for different lines in this chart.
For a line chart with just one line, this can be:
- None, to use the default color.
- A hex string like "#ffaa00" or "#ffaa0088".
- An RGB or RGBA tuple with the red, green, blue, and alpha
components specified as ints from 0 to 255 or floats from 0.0 to
1.0.
For a line chart with multiple lines, where the dataframe is in
long format (that is, y is None or just one column), this can be:
- None, to use the default colors.
- The name of a column in the dataset. Data points will be grouped
into lines of the same color based on the value of this column.
In addition, if the values in this column match one of the color
formats above (hex string or color tuple), then that color will
be used.
For example: if the dataset has 1000 rows, but this column only
contains the values "adult", "child", and "baby", then those 1000
datapoints will be grouped into three lines whose colors will be
automatically selected from the default palette.
But, if for the same 1000-row dataset, this column contained
the values "#ffaa00", "#f0f", "#0000ff", then then those 1000
datapoints would still be grouped into three lines, but their
colors would be "#ffaa00", "#f0f", "#0000ff" this time around.
For a line chart with multiple lines, where the dataframe is in
wide format (that is, y is a Sequence of columns), this can be:
- None, to use the default colors.
- A list of string colors or color tuples to be used for each of
the lines in the chart. This list should have the same length
as the number of y values (e.g. ``color=["#fd0", "#f0f", "#04f"]``
for three lines).
You can set the default colors in the ``theme.chartCategoryColors``
configuration option.
width : "stretch", "content", or int
The width of the chart element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- ``"content"``: The width of the element matches the width of its
content, but doesn't exceed the width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
height : "content", "stretch", or int
The height of the chart element. This can be one of the following:
- ``"content"`` (default): The height of the element matches the
height of its content.
- ``"stretch"``: The height of the element matches the height of
its content or the height of the parent container, whichever is
larger. If the element is not in a parent container, the height
of the element matches the height of its content.
- An integer specifying the height in pixels: The element has a
fixed height. If the content is larger than the specified
height, scrolling is enabled.
use_container_width : bool or None
Whether to override the chart's native width with the width of
the parent container. This can be one of the following:
- ``None`` (default): Streamlit will use the chart's default behavior.
- ``True``: Streamlit sets the width of the chart to match the
width of the parent container.
- ``False``: Streamlit sets the width of the chart to fit its
contents according to the plotting library, up to the width of
the parent container.
.. deprecated::
``use_container_width`` is deprecated and will be removed in a
future release. For ``use_container_width=True``, use
``width="stretch"``.
Examples
--------
**Example 1: Basic line chart from a dataframe**
If you don't use any of the optional parameters, Streamlit plots each
column as a separate line, uses the index as the x values, and labels
each series with the column name:
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(rng(0).standard_normal((20, 3)), columns=["a", "b", "c"])
>>>
>>> st.line_chart(df)
.. output::
https://doc-line-chart.streamlit.app/
height: 440px
**Example 2: Line chart from specific dataframe columns**
You can choose different columns to use for the x and y values. If your
dataframe is in long format (all y-values in one column), you can set
the line colors from another column.
If the column contains color strings, the colors will be applied
directly and the series will be unlabeled. If the column contains other
values, those values will label each line, and the line colors will be
selected from the default color palette. You can configure this color
palette in the ``theme.chartCategoryColors`` configuration option.
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(
... {
... "col1": list(range(20)) * 3,
... "col2": rng(0).standard_normal(60),
... "col3": ["a"] * 20 + ["b"] * 20 + ["c"] * 20,
... }
... )
>>>
>>> st.line_chart(df, x="col1", y="col2", color="col3")
.. output::
https://doc-line-chart1.streamlit.app/
height: 440px
**Example 3: Line chart from wide-format dataframe**
If your dataframe is in wide format (y-values are in multiple columns),
you can pass a list of columns to the ``y`` parameter. Each column
name becomes a series label. To override the default colors, pass a
list of colors to the ``color`` parameter, one for each series:
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(rng(0).standard_normal((20, 3)), columns=["a", "b", "c"])
>>>
>>> st.line_chart(
... df,
... x="a",
... y=["b", "c"],
... color=["#FF0000", "#0000FF"],
... )
.. output::
https://doc-line-chart2.streamlit.app/
height: 440px
"""
chart, add_rows_metadata = generate_chart(
chart_type=ChartType.LINE,
data=data,
x_from_user=x,
y_from_user=y,
x_axis_label=x_label,
y_axis_label=y_label,
color_from_user=color,
size_from_user=None,
width=width,
height=height,
use_container_width=(width == "stretch"),
)
return cast(
"DeltaGenerator",
self._altair_chart(
chart,
use_container_width=use_container_width,
theme="streamlit",
add_rows_metadata=add_rows_metadata,
width=width,
height=height,
),
)
@gather_metrics("area_chart")
def area_chart(
self,
data: Data = None,
*,
x: str | None = None,
y: str | Sequence[str] | None = None,
x_label: str | None = None,
y_label: str | None = None,
color: str | Color | list[Color] | None = None,
stack: bool | ChartStackType | None = None,
width: Width = "stretch",
height: Height = "content",
use_container_width: bool | None = None,
) -> DeltaGenerator:
"""Display an area chart.
This is syntax-sugar around ``st.altair_chart``. The main difference
is this command uses the data's own column and indices to figure out
the chart's Altair spec. As a result this is easier to use for many
"just plot this" scenarios, while being less customizable.
Parameters
----------
data : Anything supported by st.dataframe
Data to be plotted.
x : str or None
Column name or key associated to the x-axis data. If ``x`` is
``None`` (default), Streamlit uses the data index for the x-axis
values.
y : str, Sequence of str, or None
Column name(s) or key(s) associated to the y-axis data. If this is
``None`` (default), Streamlit draws the data of all remaining
columns as data series. If this is a ``Sequence`` of strings,
Streamlit draws several series on the same chart by melting your
wide-format table into a long-format table behind the scenes.
x_label : str or None
The label for the x-axis. If this is ``None`` (default), Streamlit
will use the column name specified in ``x`` if available, or else
no label will be displayed.
y_label : str or None
The label for the y-axis. If this is ``None`` (default), Streamlit
will use the column name(s) specified in ``y`` if available, or
else no label will be displayed.
color : str, tuple, Sequence of str, Sequence of tuple, or None
The color to use for different series in this chart.
For an area chart with just 1 series, this can be:
- None, to use the default color.
- A hex string like "#ffaa00" or "#ffaa0088".
- An RGB or RGBA tuple with the red, green, blue, and alpha
components specified as ints from 0 to 255 or floats from 0.0 to
1.0.
For an area chart with multiple series, where the dataframe is in
long format (that is, y is None or just one column), this can be:
- None, to use the default colors.
- The name of a column in the dataset. Data points will be grouped
into series of the same color based on the value of this column.
In addition, if the values in this column match one of the color
formats above (hex string or color tuple), then that color will
be used.
For example: if the dataset has 1000 rows, but this column only
contains the values "adult", "child", and "baby", then those 1000
datapoints will be grouped into three series whose colors will be
automatically selected from the default palette.
But, if for the same 1000-row dataset, this column contained
the values "#ffaa00", "#f0f", "#0000ff", then then those 1000
datapoints would still be grouped into 3 series, but their
colors would be "#ffaa00", "#f0f", "#0000ff" this time around.
For an area chart with multiple series, where the dataframe is in
wide format (that is, y is a Sequence of columns), this can be:
- None, to use the default colors.
- A list of string colors or color tuples to be used for each of
the series in the chart. This list should have the same length
as the number of y values (e.g. ``color=["#fd0", "#f0f", "#04f"]``
for three lines).
You can set the default colors in the ``theme.chartCategoryColors``
configuration option.
stack : bool, "normalize", "center", or None
Whether to stack the areas. If this is ``None`` (default),
Streamlit uses Vega's default. Other values can be as follows:
- ``True``: The areas form a non-overlapping, additive stack within
the chart.
- ``False``: The areas overlap each other without stacking.
- ``"normalize"``: The areas are stacked and the total height is
normalized to 100% of the height of the chart.
- ``"center"``: The areas are stacked and shifted to center their
baseline, which creates a steamgraph.
width : "stretch", "content", or int
The width of the chart element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- ``"content"``: The width of the element matches the width of its
content, but doesn't exceed the width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
height : "stretch", "content", or int
The height of the chart element. This can be one of the following:
- ``"content"`` (default): The height of the element matches the
height of its content.
- ``"stretch"``: The height of the element matches the height of
its content or the height of the parent container, whichever is
larger. If the element is not in a parent container, the height
of the element matches the height of its content.
- An integer specifying the height in pixels: The element has a
fixed height. If the content is larger than the specified
height, scrolling is enabled.
use_container_width : bool or None
Whether to override the chart's native width with the width of
the parent container. This can be one of the following:
- ``None`` (default): Streamlit will use the chart's default behavior.
- ``True``: Streamlit sets the width of the chart to match the
width of the parent container.
- ``False``: Streamlit sets the width of the chart to fit its
contents according to the plotting library, up to the width of
the parent container.
.. deprecated::
``use_container_width`` is deprecated and will be removed in a
future release. For ``use_container_width=True``, use
``width="stretch"``.
Examples
--------
**Example 1: Basic area chart from a dataframe**
If you don't use any of the optional parameters, Streamlit plots each
column as a separate area, uses the index as the x values, and labels
each series with the column name:
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(rng(0).standard_normal((20, 3)), columns=["a", "b", "c"])
>>>
>>> st.area_chart(df)
.. output::
https://doc-area-chart.streamlit.app/
height: 440px
**Example 2: Area chart from specific dataframe columns**
You can choose different columns to use for the x and y values. If your
dataframe is in long format (all y-values in one column), you can set
the area colors from another column.
If the column contains color strings, the colors will be applied
directly and the series will be unlabeled. If the column contains other
values, those values will label each area, and the area colors will be
selected from the default color palette. You can configure this color
palette in the ``theme.chartCategoryColors`` configuration option.
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(
... {
... "col1": list(range(20)) * 3,
... "col2": rng(0).standard_normal(60),
... "col3": ["a"] * 20 + ["b"] * 20 + ["c"] * 20,
... }
... )
>>>
>>> st.area_chart(df, x="col1", y="col2", color="col3")
.. output::
https://doc-area-chart1.streamlit.app/
height: 440px
**Example 3: Area chart from wide-format dataframe**
If your dataframe is in wide format (y-values are in multiple columns),
you can pass a list of columns to the ``y`` parameter. Each column
name becomes a series label. To override the default colors, pass a
list of colors to the ``color`` parameter, one for each series. If your
areas are overlapping, use colors with some transparency (alpha
channel) for the best results.
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(
... {
... "col1": list(range(20)),
... "col2": rng(0).standard_normal(20),
... "col3": rng(1).standard_normal(20),
... }
... )
>>>
>>> st.area_chart(
... df,
... x="col1",
... y=["col2", "col3"],
... color=["#FF000080", "#0000FF80"],
... )
.. output::
https://doc-area-chart2.streamlit.app/
height: 440px
**Example 4: Area chart with different stacking**
You can adjust the stacking behavior by setting ``stack``. You can
create a streamgraph by setting ``stack="center"``:
>>> import streamlit as st
>>> from vega_datasets import data
>>>
>>> df = data.unemployment_across_industries()
>>>
>>> st.area_chart(df, x="date", y="count", color="series", stack="center")
.. output::
https://doc-area-chart-steamgraph.streamlit.app/
height: 440px
"""
# Check that the stack parameter is valid, raise more informative error message if not
maybe_raise_stack_warning(
stack,
"st.area_chart",
"https://docs.streamlit.io/develop/api-reference/charts/st.area_chart",
)
# st.area_chart's stack=False option translates to a "layered" area chart for
# vega. We reserve stack=False for
# grouped/non-stacked bar charts, so we need to translate False to "layered"
# here. The default stack type was changed in vega-lite 5.14.1:
# https://github.com/vega/vega-lite/issues/9337
# To get the old behavior, we also need to set stack to layered as the
# default (if stack is None)
if stack is False or stack is None:
stack = "layered"
chart, add_rows_metadata = generate_chart(
chart_type=ChartType.AREA,
data=data,
x_from_user=x,
y_from_user=y,
x_axis_label=x_label,
y_axis_label=y_label,
color_from_user=color,
size_from_user=None,
width=width,
height=height,
stack=stack,
use_container_width=(width == "stretch"),
)
return cast(
"DeltaGenerator",
self._altair_chart(
chart,
use_container_width=use_container_width,
theme="streamlit",
add_rows_metadata=add_rows_metadata,
width=width,
height=height,
),
)
@gather_metrics("bar_chart")
def bar_chart(
self,
data: Data = None,
*,
x: str | None = None,
y: str | Sequence[str] | None = None,
x_label: str | None = None,
y_label: str | None = None,
color: str | Color | list[Color] | None = None,
horizontal: bool = False,
sort: bool | str = True,
stack: bool | ChartStackType | None = None,
width: Width = "stretch",
height: Height = "content",
use_container_width: bool | None = None,
) -> DeltaGenerator:
"""Display a bar chart.
This is syntax-sugar around ``st.altair_chart``. The main difference
is this command uses the data's own column and indices to figure out
the chart's Altair spec. As a result this is easier to use for many
"just plot this" scenarios, while being less customizable.
Parameters
----------
data : Anything supported by st.dataframe
Data to be plotted.
x : str or None
Column name or key associated to the x-axis data. If ``x`` is
``None`` (default), Streamlit uses the data index for the x-axis
values.
y : str, Sequence of str, or None
Column name(s) or key(s) associated to the y-axis data. If this is
``None`` (default), Streamlit draws the data of all remaining
columns as data series. If this is a ``Sequence`` of strings,
Streamlit draws several series on the same chart by melting your
wide-format table into a long-format table behind the scenes.
x_label : str or None
The label for the x-axis. If this is ``None`` (default), Streamlit
will use the column name specified in ``x`` if available, or else
no label will be displayed.
y_label : str or None
The label for the y-axis. If this is ``None`` (default), Streamlit
will use the column name(s) specified in ``y`` if available, or
else no label will be displayed.
color : str, tuple, Sequence of str, Sequence of tuple, or None
The color to use for different series in this chart.
For a bar chart with just one series, this can be:
- None, to use the default color.
- A hex string like "#ffaa00" or "#ffaa0088".
- An RGB or RGBA tuple with the red, green, blue, and alpha
components specified as ints from 0 to 255 or floats from 0.0 to
1.0.
For a bar chart with multiple series, where the dataframe is in
long format (that is, y is None or just one column), this can be:
- None, to use the default colors.
- The name of a column in the dataset. Data points will be grouped
into series of the same color based on the value of this column.
In addition, if the values in this column match one of the color
formats above (hex string or color tuple), then that color will
be used.
For example: if the dataset has 1000 rows, but this column only
contains the values "adult", "child", and "baby", then those 1000
datapoints will be grouped into three series whose colors will be
automatically selected from the default palette.
But, if for the same 1000-row dataset, this column contained
the values "#ffaa00", "#f0f", "#0000ff", then then those 1000
datapoints would still be grouped into 3 series, but their
colors would be "#ffaa00", "#f0f", "#0000ff" this time around.
For a bar chart with multiple series, where the dataframe is in
wide format (that is, y is a Sequence of columns), this can be:
- None, to use the default colors.
- A list of string colors or color tuples to be used for each of
the series in the chart. This list should have the same length
as the number of y values (e.g. ``color=["#fd0", "#f0f", "#04f"]``
for three lines).
You can set the default colors in the ``theme.chartCategoryColors``
configuration option.
horizontal : bool
Whether to make the bars horizontal. If this is ``False``
(default), the bars display vertically. If this is ``True``,
Streamlit swaps the x-axis and y-axis and the bars display
horizontally.
sort : bool or str
How to sort the bars. This can be one of the following:
- ``True`` (default): The bars are sorted automatically along the
independent/categorical axis with Altair's default sorting. This
also correctly sorts ordered categorical columns
(``pd.Categorical``).
- ``False``: The bars are shown in data order without sorting.
- The name of a column (e.g. ``"col1"``): The bars are sorted by
that column in ascending order.
- The name of a column with a minus-sign prefix (e.g. ``"-col1"``):
The bars are sorted by that column in descending order.
stack : bool, "normalize", "center", "layered", or None
Whether to stack the bars. If this is ``None`` (default),
Streamlit uses Vega's default. Other values can be as follows:
- ``True``: The bars form a non-overlapping, additive stack within
the chart.
- ``False``: The bars display side by side.
- ``"layered"``: The bars overlap each other without stacking.
- ``"normalize"``: The bars are stacked and the total height is
normalized to 100% of the height of the chart.
- ``"center"``: The bars are stacked and shifted to center the
total height around an axis.
width : "stretch", "content", or int
The width of the chart element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- ``"content"``: The width of the element matches the width of its
content, but doesn't exceed the width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
height : "stretch", "content", or int
The height of the chart element. This can be one of the following:
- ``"content"`` (default): The height of the element matches the
height of its content.
- ``"stretch"``: The height of the element matches the height of
its content or the height of the parent container, whichever is
larger. If the element is not in a parent container, the height
of the element matches the height of its content.
- An integer specifying the height in pixels: The element has a
fixed height. If the content is larger than the specified
height, scrolling is enabled.
use_container_width : bool or None
Whether to override the chart's native width with the width of
the parent container. This can be one of the following:
- ``None`` (default): Streamlit will use the chart's default behavior.
- ``True``: Streamlit sets the width of the chart to match the
width of the parent container.
- ``False``: Streamlit sets the width of the chart to fit its
contents according to the plotting library, up to the width of
the parent container.
.. deprecated::
``use_container_width`` is deprecated and will be removed in a
future release. For ``use_container_width=True``, use
``width="stretch"``.
Examples
--------
**Example 1: Basic bar chart from a dataframe**
If you don't use any of the optional parameters, Streamlit plots each
column as a series of bars, uses the index as the x values, and labels
each series with the column name:
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(rng(0).standard_normal((20, 3)), columns=["a", "b", "c"])
>>>
>>> st.bar_chart(df)
.. output::
https://doc-bar-chart.streamlit.app/
height: 440px
**Example 2: Bar chart from specific dataframe columns**
You can choose different columns to use for the x and y values. If your
dataframe is in long format (all y-values in one column), you can set
the bar colors from another column.
If the column contains color strings, the colors will be applied
directly and the series will be unlabeled. If the column contains other
values, those values will label each series, and the bar colors will be
selected from the default color palette. You can configure this color
palette in the ``theme.chartCategoryColors`` configuration option.
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(
... {
... "col1": list(range(20)) * 3,
... "col2": rng(0).standard_normal(60),
... "col3": ["a"] * 20 + ["b"] * 20 + ["c"] * 20,
... }
... )
>>>
>>> st.bar_chart(df, x="col1", y="col2", color="col3")
.. output::
https://doc-bar-chart1.streamlit.app/
height: 440px
**Example 3: Bar chart from wide-format dataframe**
If your dataframe is in wide format (y-values are in multiple columns),
you can pass a list of columns to the ``y`` parameter. Each column
name becomes a series label. To override the default colors, pass a
list of colors to the ``color`` parameter, one for each series:
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(
... {
... "col1": list(range(20)),
... "col2": rng(0).standard_normal(20),
... "col3": rng(1).standard_normal(20),
... }
... )
>>>
>>> st.bar_chart(
... df,
... x="col1",
... y=["col2", "col3"],
... color=["#FF0000", "#0000FF"],
... )
.. output::
https://doc-bar-chart2.streamlit.app/
height: 440px
**Example 4: Horizontal bar chart**
You can use the ``horizontal`` parameter to display horizontal bars
instead of vertical bars. This is useful when you have long labels on
the x-axis, or when you want to display a large number of categories.
This example requires ``vega_datasets`` to be installed.
>>> import streamlit as st
>>> from vega_datasets import data
>>>
>>> source = data.barley()
>>>
>>> st.bar_chart(source, x="variety", y="yield", color="site", horizontal=True)
.. output::
https://doc-bar-chart-horizontal.streamlit.app/
height: 440px
**Example 5: Unstacked bar chart**
You can configure the stacking behavior of the bars by setting the
``stack`` parameter. Set it to ``False`` to display bars side by side.
This example requires ``vega_datasets`` to be installed.
>>> import streamlit as st
>>> from vega_datasets import data
>>>
>>> source = data.barley()
>>>
>>> st.bar_chart(source, x="year", y="yield", color="site", stack=False)
.. output::
https://doc-bar-chart-unstacked.streamlit.app/
height: 440px
"""
# Check that the stack parameter is valid, raise more informative error message if not
maybe_raise_stack_warning(
stack,
"st.bar_chart",
"https://docs.streamlit.io/develop/api-reference/charts/st.bar_chart",
)
# Offset encodings (used for non-stacked/grouped bar charts) are not supported in Altair < 5.0.0
if type_util.is_altair_version_less_than("5.0.0") and stack is False:
raise StreamlitAPIException(
"Streamlit does not support non-stacked (grouped) bar charts with "
"Altair 4.x. Please upgrade to Version 5."
)
bar_chart_type = (
ChartType.HORIZONTAL_BAR if horizontal else ChartType.VERTICAL_BAR
)
chart, add_rows_metadata = generate_chart(
chart_type=bar_chart_type,
data=data,
x_from_user=x,
y_from_user=y,
x_axis_label=x_label,
y_axis_label=y_label,
color_from_user=color,
size_from_user=None,
width=width,
height=height,
use_container_width=use_container_width,
stack=stack,
horizontal=horizontal,
sort_from_user=sort,
)
return cast(
"DeltaGenerator",
self._altair_chart(
chart,
use_container_width=use_container_width,
theme="streamlit",
add_rows_metadata=add_rows_metadata,
width=width,
height=height,
),
)
@gather_metrics("scatter_chart")
def scatter_chart(
self,
data: Data = None,
*,
x: str | None = None,
y: str | Sequence[str] | None = None,
x_label: str | None = None,
y_label: str | None = None,
color: str | Color | list[Color] | None = None,
size: str | float | int | None = None,
width: Width = "stretch",
height: Height = "content",
use_container_width: bool | None = None,
) -> DeltaGenerator:
"""Display a scatterplot chart.
This is syntax-sugar around ``st.altair_chart``. The main difference
is this command uses the data's own column and indices to figure out
the chart's Altair spec. As a result this is easier to use for many
"just plot this" scenarios, while being less customizable.
Parameters
----------
data : Anything supported by st.dataframe
Data to be plotted.
x : str or None
Column name or key associated to the x-axis data. If ``x`` is
``None`` (default), Streamlit uses the data index for the x-axis
values.
y : str, Sequence of str, or None
Column name(s) or key(s) associated to the y-axis data. If this is
``None`` (default), Streamlit draws the data of all remaining
columns as data series. If this is a ``Sequence`` of strings,
Streamlit draws several series on the same chart by melting your
wide-format table into a long-format table behind the scenes.
x_label : str or None
The label for the x-axis. If this is ``None`` (default), Streamlit
will use the column name specified in ``x`` if available, or else
no label will be displayed.
y_label : str or None
The label for the y-axis. If this is ``None`` (default), Streamlit
will use the column name(s) specified in ``y`` if available, or
else no label will be displayed.
color : str, tuple, Sequence of str, Sequence of tuple, or None
The color of the circles representing each datapoint.
This can be:
- None, to use the default color.
- A hex string like "#ffaa00" or "#ffaa0088".
- An RGB or RGBA tuple with the red, green, blue, and alpha
components specified as ints from 0 to 255 or floats from 0.0 to
1.0.
- The name of a column in the dataset where the color of that
datapoint will come from.
If the values in this column are in one of the color formats
above (hex string or color tuple), then that color will be used.
Otherwise, the color will be automatically picked from the
default palette.
For example: if the dataset has 1000 rows, but this column only
contains the values "adult", "child", and "baby", then those 1000
datapoints be shown using three colors from the default palette.
But if this column only contains floats or ints, then those
1000 datapoints will be shown using a colors from a continuous
color gradient.
Finally, if this column only contains the values "#ffaa00",
"#f0f", "#0000ff", then then each of those 1000 datapoints will
be assigned "#ffaa00", "#f0f", or "#0000ff" as appropriate.
If the dataframe is in wide format (that is, y is a Sequence of
columns), this can also be:
- A list of string colors or color tuples to be used for each of
the series in the chart. This list should have the same length
as the number of y values (e.g. ``color=["#fd0", "#f0f", "#04f"]``
for three series).
size : str, float, int, or None
The size of the circles representing each point.
This can be:
- A number like 100, to specify a single size to use for all
datapoints.
- The name of the column to use for the size. This allows each
datapoint to be represented by a circle of a different size.
width : "stretch", "content", or int
The width of the chart element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- ``"content"``: The width of the element matches the width of its
content, but doesn't exceed the width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
height : "stretch", "content", or int
The height of the chart element. This can be one of the following:
- ``"content"`` (default): The height of the element matches the
height of its content.
- ``"stretch"``: The height of the element matches the height of
its content or the height of the parent container, whichever is
larger. If the element is not in a parent container, the height
of the element matches the height of its content.
- An integer specifying the height in pixels: The element has a
fixed height. If the content is larger than the specified
height, scrolling is enabled.
use_container_width : bool or None
Whether to override the chart's native width with the width of
the parent container. This can be one of the following:
- ``None`` (default): Streamlit will use the chart's default behavior.
- ``True``: Streamlit sets the width of the chart to match the
width of the parent container.
- ``False``: Streamlit sets the width of the chart to fit its
contents according to the plotting library, up to the width of
the parent container.
.. deprecated::
``use_container_width`` is deprecated and will be removed in a
future release. For ``use_container_width=True``, use
``width="stretch"``.
Examples
--------
**Example 1: Basic scatter chart from a dataframe**
If you don't use any of the optional parameters, Streamlit plots each
column as a color-coded group of points, uses the index as the x
values, and labels each group with the column name:
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(rng(0).standard_normal((20, 3)), columns=["a", "b", "c"])
>>>
>>> st.scatter_chart(df)
.. output::
https://doc-scatter-chart.streamlit.app/
height: 440px
**Example 2: Scatter chart from specific dataframe columns**
You can choose different columns to use for the x and y values. If your
dataframe is in long format (all y-values in one column), you can set
the scatter point colors from another column.
If the column contains color strings, the colors will be applied
directly and each color group will be unlabeled. If the column contains
other values, those values will label each group, and the scatter point
colors will be selected from the default color palette. You can
configure this color palette in the ``theme.chartCategoryColors``
configuration option.
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(
... rng(0).standard_normal((20, 3)), columns=["col1", "col2", "col3"]
... )
>>> df["col4"] = rng(0).choice(["a", "b", "c"], 20)
>>>
>>> st.scatter_chart(
... df,
... x="col1",
... y="col2",
... color="col4",
... size="col3",
... )
.. output::
https://doc-scatter-chart1.streamlit.app/
height: 440px
**Example 3: Scatter chart from wide-format dataframe**
If your dataframe is in wide format (y-values are in multiple columns),
you can pass a list of columns to the ``y`` parameter. Each column
name becomes a group label. To override the default colors, pass a
list of colors to the ``color`` parameter, one for each group:
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(
... rng(0).standard_normal((20, 4)),
... columns=["col1", "col2", "col3", "col4"],
... )
>>>
>>> st.scatter_chart(
... df,
... x="col1",
... y=["col2", "col3"],
... size="col4",
... color=["#FF0000", "#0000FF"],
... )
.. output::
https://doc-scatter-chart2.streamlit.app/
height: 440px
"""
chart, add_rows_metadata = generate_chart(
chart_type=ChartType.SCATTER,
data=data,
x_from_user=x,
y_from_user=y,
x_axis_label=x_label,
y_axis_label=y_label,
color_from_user=color,
size_from_user=size,
width=width,
height=height,
use_container_width=(width == "stretch"),
)
return cast(
"DeltaGenerator",
self._altair_chart(
chart,
use_container_width=use_container_width,
theme="streamlit",
add_rows_metadata=add_rows_metadata,
width=width,
height=height,
),
)
# When on_select=Ignore, return DeltaGenerator.
@overload
def altair_chart(
self,
altair_chart: AltairChart,
*,
width: Width | None = None,
height: Height = "content",
use_container_width: bool | None = None,
theme: Literal["streamlit"] | None = "streamlit",
key: Key | None = None,
on_select: Literal["ignore"] = "ignore",
selection_mode: str | Iterable[str] | None = None,
) -> DeltaGenerator: ...
# When on_select=rerun, return VegaLiteState.
@overload
def altair_chart(
self,
altair_chart: AltairChart,
*,
width: Width | None = None,
height: Height = "content",
use_container_width: bool | None = None,
theme: Literal["streamlit"] | None = "streamlit",
key: Key | None = None,
on_select: Literal["rerun"] | WidgetCallback,
selection_mode: str | Iterable[str] | None = None,
) -> VegaLiteState: ...
@gather_metrics("altair_chart")
def altair_chart(
self,
altair_chart: AltairChart,
*,
width: Width | None = None,
height: Height = "content",
use_container_width: bool | None = None,
theme: Literal["streamlit"] | None = "streamlit",
key: Key | None = None,
on_select: Literal["rerun", "ignore"] | WidgetCallback = "ignore",
selection_mode: str | Iterable[str] | None = None,
) -> DeltaGenerator | VegaLiteState:
"""Display a chart using the Vega-Altair library.
`Vega-Altair <https://altair-viz.github.io/>`_ is a declarative
statistical visualization library for Python, based on Vega and
Vega-Lite.
Parameters
----------
altair_chart : altair.Chart
The Altair chart object to display. See
https://altair-viz.github.io/gallery/ for examples of graph
descriptions.
width : "stretch", "content", int, or None
The width of the chart element. This can be one of the following:
- ``"stretch"``: The width of the element matches the width of the
parent container.
- ``"content"``: The width of the element matches the width of its
content, but doesn't exceed the width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
- ``None`` (default): Streamlit uses ``"stretch"`` for most charts,
and uses ``"content"`` for the following multi-view charts:
- Facet charts: the spec contains ``"facet"`` or encodings for
``"row"``, ``"column"``, or ``"facet"``.
- Horizontal concatenation charts: the spec contains
``"hconcat"``.
- Repeat charts: the spec contains ``"repeat"``.
height : "content", "stretch", or int
The height of the chart element. This can be one of the following:
- ``"content"`` (default): The height of the element matches the
height of its content.
- ``"stretch"``: The height of the element matches the height of
its content or the height of the parent container, whichever is
larger. If the element is not in a parent container, the height
of the element matches the height of its content.
- An integer specifying the height in pixels: The element has a
fixed height. If the content is larger than the specified
height, scrolling is enabled.
use_container_width : bool or None
Whether to override the chart's native width with the width of
the parent container. This can be one of the following:
- ``None`` (default): Streamlit will use the parent container's
width for all charts except those with known incompatibility
(``altair.Facet``, ``altair.HConcatChart``, and
``altair.RepeatChart``).
- ``True``: Streamlit sets the width of the chart to match the
width of the parent container.
- ``False``: Streamlit sets the width of the chart to fit its
contents according to the plotting library, up to the width of
the parent container.
.. deprecated::
``use_container_width`` is deprecated and will be removed in a
future release. For ``use_container_width=True``, use
``width="stretch"``.
theme : "streamlit" or None
The theme of the chart. If ``theme`` is ``"streamlit"`` (default),
Streamlit uses its own design default. If ``theme`` is ``None``,
Streamlit falls back to the default behavior of the library.
The ``"streamlit"`` theme can be partially customized through the
configuration options ``theme.chartCategoricalColors`` and
``theme.chartSequentialColors``. Font configuration options are
also applied.
key : str
An optional string to use for giving this element a stable
identity. If ``key`` is ``None`` (default), this element's identity
will be determined based on the values of the other parameters.
Additionally, if selections are activated and ``key`` is provided,
Streamlit will register the key in Session State to store the
selection state. The selection state is read-only.
on_select : "ignore", "rerun", or callable
How the figure should respond to user selection events. This
controls whether or not the figure behaves like an input widget.
``on_select`` can be one of the following:
- ``"ignore"`` (default): Streamlit will not react to any selection
events in the chart. The figure will not behave like an input
widget.
- ``"rerun"``: Streamlit will rerun the app when the user selects
data in the chart. In this case, ``st.altair_chart`` will return
the selection data as a dictionary.
- A ``callable``: Streamlit will rerun the app and execute the
``callable`` as a callback function before the rest of the app.
In this case, ``st.altair_chart`` will return the selection data
as a dictionary.
To use selection events, the object passed to ``altair_chart`` must
include selection parameters. To learn about defining interactions
in Altair and how to declare selection-type parameters, see
`Interactive Charts \
<https://altair-viz.github.io/user_guide/interactions.html>`_
in Altair's documentation.
selection_mode : str or Iterable of str
The selection parameters Streamlit should use. If
``selection_mode`` is ``None`` (default), Streamlit will use all
selection parameters defined in the chart's Altair spec.
When Streamlit uses a selection parameter, selections from that
parameter will trigger a rerun and be included in the selection
state. When Streamlit does not use a selection parameter,
selections from that parameter will not trigger a rerun and not be
included in the selection state.
Selection parameters are identified by their ``name`` property.
Returns
-------
element or dict
If ``on_select`` is ``"ignore"`` (default), this command returns an
internal placeholder for the chart element that can be used with
the ``.add_rows()`` method. Otherwise, this command returns a
dictionary-like object that supports both key and attribute
notation. The attributes are described by the ``VegaLiteState``
dictionary schema.
Example
-------
>>> import altair as alt
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(rng(0).standard_normal((60, 3)), columns=["a", "b", "c"])
>>>
>>> chart = (
... alt.Chart(df)
... .mark_circle()
... .encode(x="a", y="b", size="c", color="c", tooltip=["a", "b", "c"])
... )
>>>
>>> st.altair_chart(chart)
.. output::
https://doc-vega-lite-chart.streamlit.app/
height: 450px
"""
return self._altair_chart(
altair_chart=altair_chart,
width=width,
height=height,
use_container_width=use_container_width,
theme=theme,
key=key,
on_select=on_select,
selection_mode=selection_mode,
)
# When on_select=Ignore, return DeltaGenerator.
@overload
def vega_lite_chart(
self,
data: Data = None,
spec: VegaLiteSpec | None = None,
*,
width: Width | None = None,
height: Height = "content",
use_container_width: bool | None = None,
theme: Literal["streamlit"] | None = "streamlit",
key: Key | None = None,
on_select: Literal["ignore"] = "ignore",
selection_mode: str | Iterable[str] | None = None,
**kwargs: Any,
) -> DeltaGenerator: ...
# When on_select=rerun, return VegaLiteState.
@overload
def vega_lite_chart(
self,
data: Data = None,
spec: VegaLiteSpec | None = None,
*,
width: Width | None = None,
height: Height = "content",
use_container_width: bool | None = None,
theme: Literal["streamlit"] | None = "streamlit",
key: Key | None = None,
on_select: Literal["rerun"] | WidgetCallback,
selection_mode: str | Iterable[str] | None = None,
**kwargs: Any,
) -> VegaLiteState: ...
@gather_metrics("vega_lite_chart")
def vega_lite_chart(
self,
data: Data = None,
spec: VegaLiteSpec | None = None,
*,
width: Width | None = None,
height: Height = "content",
use_container_width: bool | None = None,
theme: Literal["streamlit"] | None = "streamlit",
key: Key | None = None,
on_select: Literal["rerun", "ignore"] | WidgetCallback = "ignore",
selection_mode: str | Iterable[str] | None = None,
**kwargs: Any,
) -> DeltaGenerator | VegaLiteState:
"""Display a chart using the Vega-Lite library.
`Vega-Lite <https://vega.github.io/vega-lite/>`_ is a high-level
grammar for defining interactive graphics.
Parameters
----------
data : Anything supported by st.dataframe
Either the data to be plotted or a Vega-Lite spec containing the
data (which more closely follows the Vega-Lite API).
spec : dict or None
The Vega-Lite spec for the chart. If ``spec`` is ``None`` (default),
Streamlit uses the spec passed in ``data``. You cannot pass a spec
to both ``data`` and ``spec``. See
https://vega.github.io/vega-lite/docs/ for more info.
width : "stretch", "content", int, or None
The width of the chart element. This can be one of the following:
- ``"stretch"``: The width of the element matches the width of the
parent container.
- ``"content"``: The width of the element matches the width of its
content, but doesn't exceed the width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
- ``None`` (default): Streamlit uses ``"stretch"`` for most charts,
and uses ``"content"`` for the following multi-view charts:
- Facet charts: the spec contains ``"facet"`` or encodings for
``"row"``, ``"column"``, or ``"facet"``.
- Horizontal concatenation charts: the spec contains
``"hconcat"``.
- Repeat charts: the spec contains ``"repeat"``.
height : "content", "stretch", or int
The height of the chart element. This can be one of the following:
- ``"content"`` (default): The height of the element matches the
height of its content.
- ``"stretch"``: The height of the element matches the height of
its content or the height of the parent container, whichever is
larger. If the element is not in a parent container, the height
of the element matches the height of its content.
- An integer specifying the height in pixels: The element has a
fixed height. If the content is larger than the specified
height, scrolling is enabled.
use_container_width : bool or None
Whether to override the chart's native width with the width of
the parent container. This can be one of the following:
- ``None`` (default): Streamlit will use the parent container's
width for all charts except those with known incompatibility
(``altair.Facet``, ``altair.HConcatChart``, and
``altair.RepeatChart``).
- ``True``: Streamlit sets the width of the chart to match the
width of the parent container.
- ``False``: Streamlit sets the width of the chart to fit its
contents according to the plotting library, up to the width of
the parent container.
.. deprecated::
``use_container_width`` is deprecated and will be removed in a
future release. For ``use_container_width=True``, use
``width="stretch"``.
theme : "streamlit" or None
The theme of the chart. If ``theme`` is ``"streamlit"`` (default),
Streamlit uses its own design default. If ``theme`` is ``None``,
Streamlit falls back to the default behavior of the library.
The ``"streamlit"`` theme can be partially customized through the
configuration options ``theme.chartCategoricalColors`` and
``theme.chartSequentialColors``. Font configuration options are
also applied.
key : str
An optional string to use for giving this element a stable
identity. If ``key`` is ``None`` (default), this element's identity
will be determined based on the values of the other parameters.
Additionally, if selections are activated and ``key`` is provided,
Streamlit will register the key in Session State to store the
selection state. The selection state is read-only.
on_select : "ignore", "rerun", or callable
How the figure should respond to user selection events. This
controls whether or not the figure behaves like an input widget.
``on_select`` can be one of the following:
- ``"ignore"`` (default): Streamlit will not react to any selection
events in the chart. The figure will not behave like an input
widget.
- ``"rerun"``: Streamlit will rerun the app when the user selects
data in the chart. In this case, ``st.vega_lite_chart`` will
return the selection data as a dictionary.
- A ``callable``: Streamlit will rerun the app and execute the
``callable`` as a callback function before the rest of the app.
In this case, ``st.vega_lite_chart`` will return the selection data
as a dictionary.
To use selection events, the Vega-Lite spec defined in ``data`` or
``spec`` must include selection parameters from the charting
library. To learn about defining interactions in Vega-Lite, see
`Dynamic Behaviors with Parameters \
<https://vega.github.io/vega-lite/docs/parameter.html>`_
in Vega-Lite's documentation.
selection_mode : str or Iterable of str
The selection parameters Streamlit should use. If
``selection_mode`` is ``None`` (default), Streamlit will use all
selection parameters defined in the chart's Vega-Lite spec.
When Streamlit uses a selection parameter, selections from that
parameter will trigger a rerun and be included in the selection
state. When Streamlit does not use a selection parameter,
selections from that parameter will not trigger a rerun and not be
included in the selection state.
Selection parameters are identified by their ``name`` property.
**kwargs : any
The Vega-Lite spec for the chart as keywords. This is an alternative
to ``spec``.
.. deprecated::
``**kwargs`` are deprecated and will be removed in a future
release. To specify Vega-Lite configuration options, use the
``spec`` argument instead.
Returns
-------
element or dict
If ``on_select`` is ``"ignore"`` (default), this command returns an
internal placeholder for the chart element that can be used with
the ``.add_rows()`` method. Otherwise, this command returns a
dictionary-like object that supports both key and attribute
notation. The attributes are described by the ``VegaLiteState``
dictionary schema.
Example
-------
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(rng(0).standard_normal((60, 3)), columns=["a", "b", "c"])
>>>
>>> st.vega_lite_chart(
... df,
... {
... "mark": {"type": "circle", "tooltip": True},
... "encoding": {
... "x": {"field": "a", "type": "quantitative"},
... "y": {"field": "b", "type": "quantitative"},
... "size": {"field": "c", "type": "quantitative"},
... "color": {"field": "c", "type": "quantitative"},
... },
... },
... )
.. output::
https://doc-vega-lite-chart.streamlit.app/
height: 450px
Examples of Vega-Lite usage without Streamlit can be found at
https://vega.github.io/vega-lite/examples/. Most of those can be easily
translated to the syntax shown above.
"""
if kwargs:
show_deprecation_warning(
"Variable keyword arguments for `st.vega_lite_chart` have been "
"deprecated and will be removed in a future release. Use the "
"`spec` argument instead to specify Vega-Lite configuration "
"options."
)
return self._vega_lite_chart(
data=data,
spec=spec,
use_container_width=use_container_width,
theme=theme,
key=key,
on_select=on_select,
selection_mode=selection_mode,
width=width,
height=height,
**kwargs,
)
def _altair_chart(
self,
altair_chart: AltairChart,
use_container_width: bool | None = None,
theme: Literal["streamlit"] | None = "streamlit",
key: Key | None = None,
on_select: Literal["rerun", "ignore"] | WidgetCallback = "ignore",
selection_mode: str | Iterable[str] | None = None,
add_rows_metadata: AddRowsMetadata | None = None,
width: Width | None = None,
height: Height = "content",
) -> DeltaGenerator | VegaLiteState:
"""Internal method to enqueue a vega-lite chart element based on an Altair chart.
See the `altair_chart` method docstring for more information.
"""
if type_util.is_altair_version_less_than("5.0.0") and on_select != "ignore":
raise StreamlitAPIException(
"Streamlit does not support selections with Altair 4.x. Please upgrade "
"to Version 5. "
"If you would like to use Altair 4.x with selections, please upvote "
"this [Github issue](https://github.com/streamlit/streamlit/issues/8516)."
)
vega_lite_spec = _convert_altair_to_vega_lite_spec(altair_chart)
return self._vega_lite_chart(
data=None, # The data is already part of the spec
spec=vega_lite_spec,
use_container_width=use_container_width,
theme=theme,
key=key,
on_select=on_select,
selection_mode=selection_mode,
add_rows_metadata=add_rows_metadata,
width=width,
height=height,
)
def _vega_lite_chart(
self,
data: Data = None,
spec: VegaLiteSpec | None = None,
use_container_width: bool | None = None,
theme: Literal["streamlit"] | None = "streamlit",
key: Key | None = None,
on_select: Literal["rerun", "ignore"] | WidgetCallback = "ignore",
selection_mode: str | Iterable[str] | None = None,
add_rows_metadata: AddRowsMetadata | None = None,
width: Width | None = None,
height: Height = "content",
**kwargs: Any,
) -> DeltaGenerator | VegaLiteState:
"""Internal method to enqueue a vega-lite chart element based on a vega-lite spec.
See the `vega_lite_chart` method docstring for more information.
"""
if theme not in ["streamlit", None]:
raise StreamlitAPIException(
f'You set theme="{theme}" while Streamlit charts only support '
"theme=”streamlit” or theme=None to fallback to the default "
"library theme."
)
if on_select not in ["ignore", "rerun"] and not callable(on_select):
raise StreamlitAPIException(
f"You have passed {on_select} to `on_select`. But only 'ignore', "
"'rerun', or a callable is supported."
)
key = to_key(key)
is_selection_activated = on_select != "ignore"
if is_selection_activated:
# Run some checks that are only relevant when selections are activated
is_callback = callable(on_select)
check_widget_policies(
self.dg,
key,
on_change=cast("WidgetCallback", on_select) if is_callback else None,
default_value=None,
writes_allowed=False,
enable_check_callback_rules=is_callback,
)
# Support passing data inside spec['datasets'] and spec['data'].
# (The data gets pulled out of the spec dict later on.)
if isinstance(data, dict) and spec is None:
spec = data
data = None
if spec is None:
spec = {}
# Set the default value for width. Altair and Vega charts have different defaults depending on the chart type,
# so they don't default the value in the function signature and width could be None here.
if use_container_width is None and width is None:
# Some multi-view charts (facet, horizontal concatenation, and repeat;
# see https://altair-viz.github.io/user_guide/compound_charts.html)
# don't work well with `width=stretch`, so we disable it for
# those charts (see https://github.com/streamlit/streamlit/issues/9091).
# All other charts (including vertical concatenation) default to
# `width=stretch` unless width is provided.
is_facet_chart = "facet" in spec or (
"encoding" in spec
and (any(x in spec["encoding"] for x in ["row", "column", "facet"]))
)
width = (
"stretch"
if not (is_facet_chart or "hconcat" in spec or "repeat" in spec)
else "content"
)
if use_container_width is not None:
show_deprecation_warning(
make_deprecated_name_warning(
"use_container_width",
"width",
"2025-12-31",
"For `use_container_width=True`, use `width='stretch'`. "
"For `use_container_width=False`, use `width='content'` or specify an integer width.",
include_st_prefix=False,
),
show_in_browser=False,
)
if use_container_width:
width = "stretch"
elif not isinstance(width, int):
# No specific width provided, use content width
width = "content"
# Otherwise keep the integer width - user explicitly set both use_container_width=False and width=int
if width is not None:
validate_width(width, allow_content=True)
validate_height(height, allow_content=True)
vega_lite_proto = ArrowVegaLiteChartProto()
use_container_width_for_spec = (
use_container_width
if use_container_width is not None
else width == "stretch"
)
spec = _prepare_vega_lite_spec(spec, use_container_width_for_spec, **kwargs)
_marshall_chart_data(vega_lite_proto, spec, data)
# Prevent the spec from changing across reruns:
vega_lite_proto.spec = _stabilize_vega_json_spec(json.dumps(spec))
if use_container_width is not None:
vega_lite_proto.use_container_width = use_container_width
vega_lite_proto.theme = theme or ""
if is_selection_activated:
# Load the stabilized spec again as a dict:
final_spec = json.loads(vega_lite_proto.spec)
# Temporary limitation to disallow multi-view charts (compositions) with selections.
_disallow_multi_view_charts(final_spec)
# Parse and check the specified selection modes
parsed_selection_modes = _parse_selection_mode(final_spec, selection_mode)
vega_lite_proto.selection_mode.extend(parsed_selection_modes)
vega_lite_proto.form_id = current_form_id(self.dg)
ctx = get_script_run_ctx()
vega_lite_proto.id = compute_and_register_element_id(
"arrow_vega_lite_chart",
user_key=key,
key_as_main_identity=False,
dg=self.dg,
vega_lite_spec=vega_lite_proto.spec,
# The data is either in vega_lite_proto.data.data
# or in a named dataset in vega_lite_proto.datasets
vega_lite_data=vega_lite_proto.data.data,
# Its enough to just use the names here since they are expected
# to contain hashes based on the dataset data.
named_datasets=[dataset.name for dataset in vega_lite_proto.datasets],
theme=theme,
use_container_width=use_container_width,
selection_mode=parsed_selection_modes,
)
serde = VegaLiteStateSerde(parsed_selection_modes)
widget_state = register_widget(
vega_lite_proto.id,
on_change_handler=on_select if callable(on_select) else None,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="string_value",
)
layout_config = LayoutConfig(width=width, height=height)
self.dg._enqueue(
"arrow_vega_lite_chart",
vega_lite_proto,
add_rows_metadata=add_rows_metadata,
layout_config=layout_config,
)
return widget_state.value
# If its not used with selections activated, just return
# the delta generator related to this element.
layout_config = LayoutConfig(width=width, height=height)
return self.dg._enqueue(
"arrow_vega_lite_chart",
vega_lite_proto,
add_rows_metadata=add_rows_metadata,
layout_config=layout_config,
)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
def _to_arrow_dataset(data: Any, datasets: dict[str, Any]) -> dict[str, str]:
"""Altair data transformer that serializes the data,
creates a stable name based on the hash of the data,
stores the bytes into the datasets mapping and
returns this name to have it be used in Altair.
"""
# Already serialize the data to be able to create a stable
# dataset name:
data_bytes = dataframe_util.convert_anything_to_arrow_bytes(data)
# Use the md5 hash of the data as the name:
name = calc_md5(str(data_bytes))
datasets[name] = data_bytes
return {"name": name}
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/image.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
# Some casts in this file are only occasionally necessary depending on the
# user's Python version, and mypy doesn't have a good way of toggling this
# specific config option at a per-line level.
# mypy: no-warn-unused-ignores
"""Image marshalling."""
from __future__ import annotations
from typing import TYPE_CHECKING, Literal, TypeAlias, cast
from streamlit.deprecation_util import (
make_deprecated_name_warning,
show_deprecation_warning,
)
from streamlit.elements.lib.image_utils import (
Channels,
ImageFormatOrAuto,
ImageOrImageList,
marshall_images,
)
from streamlit.elements.lib.layout_utils import LayoutConfig, Width, validate_width
from streamlit.errors import StreamlitAPIException
from streamlit.proto.Image_pb2 import ImageList as ImageListProto
from streamlit.runtime.metrics_util import gather_metrics
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
UseColumnWith: TypeAlias = Literal["auto", "always", "never"] | bool | None
class ImageMixin:
@gather_metrics("image")
def image(
self,
image: ImageOrImageList,
# TODO: Narrow type of caption, dependent on type of image,
# by way of overload
caption: str | list[str] | None = None,
width: Width = "content",
use_column_width: UseColumnWith = None,
clamp: bool = False,
channels: Channels = "RGB",
output_format: ImageFormatOrAuto = "auto",
*,
use_container_width: bool | None = None,
) -> DeltaGenerator:
"""Display an image or list of images.
Parameters
----------
image : numpy.ndarray, BytesIO, str, Path, or list of these
The image to display. This can be one of the following:
- A URL (string) for a hosted image.
- A path to a local image file. The path can be a ``str``
or ``Path`` object. Paths can be absolute or relative to the
working directory (where you execute ``streamlit run``).
- An SVG string like ``<svg xmlns=...</svg>``.
- A byte array defining an image. This includes monochrome images of
shape (w,h) or (w,h,1), color images of shape (w,h,3), or RGBA
images of shape (w,h,4), where w and h are the image width and
height, respectively.
- A list of any of the above. Streamlit displays the list as a
row of images that overflow to additional rows as needed.
caption : str or list of str
Image caption(s). If this is ``None`` (default), no caption is
displayed. If ``image`` is a list of multiple images, ``caption``
must be a list of captions (one caption for each image) or
``None``.
Captions can optionally contain GitHub-flavored Markdown. Syntax
information can be found at: https://github.github.com/gfm.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
width : "content", "stretch", or int
The width of the image element. This can be one of the following:
- ``"content"`` (default): The width of the element matches the
width of its content, but doesn't exceed the width of the parent
container.
- ``"stretch"``: The width of the element matches the width of the
parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
When using an SVG image without a default width, use ``"stretch"``
or an integer.
use_column_width : "auto", "always", "never", or bool
If "auto", set the image's width to its natural size,
but do not exceed the width of the column.
If "always" or True, set the image's width to the column width.
If "never" or False, set the image's width to its natural size.
Note: if set, `use_column_width` takes precedence over the `width` parameter.
.. deprecated::
``use_column_width`` is deprecated and will be removed in a future
release. Please use the ``width`` parameter instead.
clamp : bool
Whether to clamp image pixel values to a valid range (0-255 per
channel). This is only used for byte array images; the parameter is
ignored for image URLs and files. If this is ``False`` (default)
and an image has an out-of-range value, a ``RuntimeError`` will be
raised.
channels : "RGB" or "BGR"
The color format when ``image`` is an ``nd.array``. This is ignored
for other image types. If this is ``"RGB"`` (default),
``image[:, :, 0]`` is the red channel, ``image[:, :, 1]`` is the
green channel, and ``image[:, :, 2]`` is the blue channel. For
images coming from libraries like OpenCV, you should set this to
``"BGR"`` instead.
output_format : "JPEG", "PNG", or "auto"
The output format to use when transferring the image data. If this
is ``"auto"`` (default), Streamlit identifies the compression type
based on the type and format of the image. Photos should use the
``"JPEG"`` format for lossy compression while diagrams should use
the ``"PNG"`` format for lossless compression.
use_container_width : bool
Whether to override ``width`` with the width of the parent
container. If ``use_container_width`` is ``False`` (default),
Streamlit sets the image's width according to ``width``. If
``use_container_width`` is ``True``, Streamlit sets the width of
the image to match the width of the parent container.
.. deprecated::
``use_container_width`` is deprecated and will be removed in a
future release. For ``use_container_width=True``, use
``width="stretch"``. For ``use_container_width=False``, use
``width="content"``.
Example
-------
>>> import streamlit as st
>>> st.image("sunrise.jpg", caption="Sunrise by the mountains")
.. output::
https://doc-image.streamlit.app/
height: 710px
"""
if use_column_width is not None:
if use_container_width is not None:
raise StreamlitAPIException(
"`use_container_width` and `use_column_width` cannot be set at the same time.",
"Please utilize `use_container_width` since `use_column_width` is deprecated.",
)
show_deprecation_warning(
"The `use_column_width` parameter has been deprecated and will be removed "
"in a future release. Please utilize the `width` parameter instead."
)
if use_column_width in {"auto", "never"} or use_column_width is False:
width = "content"
elif use_column_width == "always" or use_column_width is True:
width = "stretch"
if use_container_width is not None:
show_deprecation_warning(
make_deprecated_name_warning(
"use_container_width",
"width",
"2025-12-31",
"For `use_container_width=True`, use `width='stretch'`. "
"For `use_container_width=False`, use `width='content'`.",
include_st_prefix=False,
),
show_in_browser=False,
)
if use_container_width is True:
width = "stretch"
elif isinstance(width, int):
# Preserve the existing behavior with respect to use_container_width=False
# and width=int.
pass
else:
width = "content"
validate_width(width, allow_content=True)
layout_config = LayoutConfig(width=width)
image_list_proto = ImageListProto()
marshall_images(
self.dg._get_delta_path_str(),
image,
caption,
layout_config,
image_list_proto,
clamp,
channels,
output_format,
)
return self.dg._enqueue("imgs", image_list_proto, layout_config=layout_config)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/exception.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import os
import traceback
from typing import TYPE_CHECKING, Final, TypeVar, cast
from streamlit import config
from streamlit.elements.lib.layout_utils import validate_width
from streamlit.errors import (
MarkdownFormattedException,
StreamlitAPIWarning,
)
from streamlit.logger import get_logger
from streamlit.proto.Exception_pb2 import Exception as ExceptionProto
from streamlit.proto.WidthConfig_pb2 import WidthConfig
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner_utils.script_run_context import get_script_run_ctx
if TYPE_CHECKING:
from collections.abc import Callable
from streamlit.delta_generator import DeltaGenerator
from streamlit.elements.lib.layout_utils import WidthWithoutContent
_LOGGER: Final = get_logger(__name__)
# When client.showErrorDetails is False, we show a generic warning in the
# frontend when we encounter an uncaught app exception.
_GENERIC_UNCAUGHT_EXCEPTION_TEXT: Final = (
"This app has encountered an error. The original error message is redacted "
"to prevent data leaks. Full error details have been recorded in the logs "
"(if you're on Streamlit Cloud, click on 'Manage app' in the lower right of your app)."
)
class ExceptionMixin:
@gather_metrics("exception")
def exception(
self, exception: BaseException, width: WidthWithoutContent = "stretch"
) -> DeltaGenerator:
"""Display an exception.
When accessing the app through ``localhost``, in the lower-right corner
of the exception, Streamlit displays links to Google and ChatGPT that
are prefilled with the contents of the exception message.
Parameters
----------
exception : Exception
The exception to display.
width : "stretch" or int
The width of the exception element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
Example
-------
>>> import streamlit as st
>>>
>>> e = RuntimeError("This is an exception of type RuntimeError")
>>> st.exception(e)
.. output::
https://doc-status-exception.streamlit.app/
height: 220px
"""
return _exception(self.dg, exception, width=width)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
# TODO(lawilby): confirm whether we want to track metrics here with lukasmasuch.
@gather_metrics("exception")
def _exception(
dg: DeltaGenerator,
exception: BaseException,
width: WidthWithoutContent = "stretch",
is_uncaught_app_exception: bool = False,
) -> DeltaGenerator:
exception_proto = ExceptionProto()
marshall(exception_proto, exception, width, is_uncaught_app_exception)
return dg._enqueue("exception", exception_proto)
def marshall(
exception_proto: ExceptionProto,
exception: BaseException,
width: WidthWithoutContent = "stretch",
is_uncaught_app_exception: bool = False,
) -> None:
"""Marshalls an Exception.proto message.
Parameters
----------
exception_proto : Exception.proto
The Exception protobuf to fill out.
exception : BaseException
The exception whose data we're extracting.
width : int or "stretch"
The width of the exception display. Can be either an integer (pixels) or "stretch".
Defaults to "stretch".
is_uncaught_app_exception: bool
The exception originates from an uncaught error during script execution.
"""
validate_width(width)
is_markdown_exception = isinstance(exception, MarkdownFormattedException)
# Some exceptions (like UserHashError) have an alternate_name attribute so
# we can pretend to the user that the exception is called something else.
if getattr(exception, "alternate_name", None) is not None:
exception_proto.type = exception.alternate_name # type: ignore[attr-defined]
else:
exception_proto.type = type(exception).__name__
stack_trace = _get_stack_trace_str_list(exception)
exception_proto.stack_trace.extend(stack_trace)
exception_proto.is_warning = isinstance(exception, Warning)
width_config = WidthConfig()
if isinstance(width, int):
width_config.pixel_width = width
else:
width_config.use_stretch = True
exception_proto.width_config.CopyFrom(width_config)
try:
if isinstance(exception, SyntaxError):
# SyntaxErrors have additional fields (filename, text, lineno,
# offset) that we can use for a nicely-formatted message telling
# the user what to fix.
exception_proto.message = _format_syntax_error_message(exception)
else:
exception_proto.message = str(exception).strip()
exception_proto.message_is_markdown = is_markdown_exception
except Exception as str_exception:
# Sometimes the exception's __str__/__unicode__ method itself
# raises an error.
exception_proto.message = ""
_LOGGER.warning(
"""
Streamlit was unable to parse the data from an exception in the user's script.
This is usually due to a bug in the Exception object itself. Here is some info
about that Exception object, so you can report a bug to the original author:
Exception type:
%s
Problem:
%s
Traceback:
%s
""",
type(exception).__name__,
str_exception,
"\n".join(_get_stack_trace_str_list(str_exception)),
)
if is_uncaught_app_exception:
show_error_details = config.get_option("client.showErrorDetails")
show_message = (
show_error_details == config.ShowErrorDetailsConfigOptions.FULL
or config.ShowErrorDetailsConfigOptions.is_true_variation(
show_error_details
)
)
# False is a legacy config option still in-use in community cloud. It is equivalent
# to "stacktrace".
show_trace = (
show_message
or show_error_details == config.ShowErrorDetailsConfigOptions.STACKTRACE
or config.ShowErrorDetailsConfigOptions.is_false_variation(
show_error_details
)
)
show_type = (
show_trace
or show_error_details == config.ShowErrorDetailsConfigOptions.TYPE
)
if not show_message:
exception_proto.message = _GENERIC_UNCAUGHT_EXCEPTION_TEXT
if not show_type:
exception_proto.ClearField("type")
else:
type_str = str(type(exception))
exception_proto.type = type_str.replace("<class '", "").replace("'>", "")
if not show_trace:
exception_proto.ClearField("stack_trace")
def _format_syntax_error_message(exception: SyntaxError) -> str:
"""Returns a nicely formatted SyntaxError message that emulates
what the Python interpreter outputs.
For example:
> File "raven.py", line 3
> st.write('Hello world!!'))
> ^
> SyntaxError: invalid syntax
"""
if exception.text:
caret_indent = (
" " * max(exception.offset - 1, 0) if exception.offset is not None else ""
)
return (
f'File "{exception.filename}", line {exception.lineno}\n'
f" {exception.text.rstrip()}\n"
f" {caret_indent}^\n"
f"{type(exception).__name__}: {exception.msg}"
)
# If a few edge cases, SyntaxErrors don't have all these nice fields. So we
# have a fall back here.
# Example edge case error message: encoding declaration in Unicode string
return str(exception)
def _get_stack_trace_str_list(exception: BaseException) -> list[str]:
"""Get the stack trace for the given exception.
Parameters
----------
exception : BaseException
The exception to extract the traceback from
Returns
-------
tuple of two string lists
The exception traceback as two lists of strings. The first represents the part
of the stack trace the users don't typically want to see, containing internal
Streamlit code. The second is whatever comes after the Streamlit stack trace,
which is usually what the user wants.
"""
extracted_traceback: traceback.StackSummary | None = None
if isinstance(exception, StreamlitAPIWarning):
extracted_traceback = exception.tacked_on_stack
elif hasattr(exception, "__traceback__"):
extracted_traceback = traceback.extract_tb(exception.__traceback__)
# Format the extracted traceback and add it to the protobuf element.
if extracted_traceback is None:
trace_str_list = [
"Cannot extract the stack trace for this exception. "
"Try calling exception() within the `catch` block."
]
else:
internal_frames, external_frames = _split_internal_streamlit_frames(
extracted_traceback
)
if external_frames:
trace_str_list = traceback.format_list(external_frames)
else:
trace_str_list = traceback.format_list(internal_frames)
trace_str_list = [item.strip() for item in trace_str_list]
return trace_str_list
def _is_in_package(file: str, package_path: str) -> bool:
"""True if the given file is part of package_path."""
try:
common_prefix = os.path.commonprefix([os.path.realpath(file), package_path])
except ValueError:
# Raised if paths are on different drives.
return False
return common_prefix == package_path
def _split_internal_streamlit_frames(
extracted_tb: traceback.StackSummary,
) -> tuple[list[traceback.FrameSummary], list[traceback.FrameSummary]]:
"""Split the traceback into a Streamlit-internal part and an external part.
The internal part is everything up to (but excluding) the first frame belonging to
the user's code. The external part is everything else.
So if the stack looks like this:
1. Streamlit frame
2. Pandas frame
3. Altair frame
4. Streamlit frame
5. User frame
6. User frame
7. Streamlit frame
8. Matplotlib frame
...then this should return 1-4 as the internal traceback and 5-8 as the external.
(Note that something like the example above is extremely unlikely to happen since
it's not like Altair is calling Streamlit code, but you get the idea.)
"""
ctx = get_script_run_ctx()
if not ctx:
return [], list(extracted_tb)
package_path = os.path.join(os.path.realpath(str(ctx.main_script_parent)), "")
return _split_list(
extracted_tb,
split_point=lambda tb: _is_in_package(tb.filename, package_path),
)
T = TypeVar("T")
def _split_list(
orig_list: list[T], split_point: Callable[[T], bool]
) -> tuple[list[T], list[T]]:
before: list[T] = []
after: list[T] = []
saw_split_point = False
for item in orig_list:
if not saw_split_point and split_point(item):
saw_split_point = True
if saw_split_point:
after.append(item)
else:
before.append(item)
return before, after
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/space.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from typing import TYPE_CHECKING, cast
from streamlit.elements.lib.layout_utils import (
LayoutConfig,
SpaceSize,
validate_space_size,
)
from streamlit.proto.Space_pb2 import Space as SpaceProto
from streamlit.runtime.metrics_util import gather_metrics
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
class SpaceMixin:
@gather_metrics("space")
def space(
self,
size: SpaceSize = "small",
) -> DeltaGenerator:
"""Add vertical or horizontal space.
This command adds space in the direction of its parent container. In
a vertical layout, it adds vertical space. In a horizontal layout, it
adds horizontal space.
Parameters
----------
size : "small", "medium", "large", "stretch", or int
The size of the space. This can be one of the following values:
- ``"small"`` (default): 0.75rem, which is the height of a widget
label. This is useful for aligning buttons with labeled widgets.
- ``"medium"``: 2.5rem, which is the height of a button or
(unlabeled) input field.
- ``"large"``: 4.25rem, which is the height of a labeled input
field or unlabeled media widget, like `st.file_uploader`.
- ``"stretch"``: Expands to fill remaining space in the container.
- An integer: Fixed size in pixels.
Examples
--------
**Example 1: Use vertical space to align elements**
Use small spaces to replace label heights. Use medium spaces to replace
two label heights or a button.
>>> import streamlit as st
>>>
>>> left, middle, right = st.columns(3)
>>>
>>> left.space("medium")
>>> left.button("Left button", width="stretch")
>>>
>>> middle.space("small")
>>> middle.text_input("Middle input")
>>>
>>> right.audio_input("Right uploader")
.. output::
https://doc-space-vertical.streamlit.app/
height: 260px
**Example 2: Add horizontal space in a container**
Use stretch space to float elements left and right.
>>> import streamlit as st
>>>
>>> with st.container(horizontal=True):
... st.button("Left")
... st.space("stretch")
... st.button("Right")
.. output::
https://doc-space-horizontal.streamlit.app/
height: 200px
"""
space_proto = SpaceProto()
validate_space_size(size)
# In vertical layouts, size controls height.
# In horizontal layouts, size controls width.
# We set both width and height configs to the same size value.
# The frontend uses FlexContext to determine container direction and
# applies ONLY the relevant dimension (width for horizontal, height for vertical)
# to avoid unintended cross-axis spacing.
layout_config = LayoutConfig(width=size, height=size)
return self.dg._enqueue("space", space_proto, layout_config=layout_config)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/layouts.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from collections.abc import Sequence
from typing import TYPE_CHECKING, Literal, TypeAlias, cast
from streamlit.delta_generator_singletons import get_dg_singleton_instance
from streamlit.elements.lib.layout_utils import (
Gap,
Height,
HorizontalAlignment,
VerticalAlignment,
Width,
WidthWithoutContent,
get_align,
get_gap_size,
get_height_config,
get_justify,
get_width_config,
validate_height,
validate_horizontal_alignment,
validate_vertical_alignment,
validate_width,
)
from streamlit.elements.lib.utils import Key, compute_and_register_element_id, to_key
from streamlit.errors import (
StreamlitAPIException,
StreamlitInvalidColumnSpecError,
StreamlitInvalidVerticalAlignmentError,
)
from streamlit.proto.Block_pb2 import Block as BlockProto
from streamlit.proto.GapSize_pb2 import GapConfig
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.string_util import validate_icon_or_emoji
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
from streamlit.elements.lib.dialog import Dialog
from streamlit.elements.lib.mutable_status_container import StatusContainer
from streamlit.runtime.state import WidgetCallback
SpecType: TypeAlias = int | Sequence[int | float]
class LayoutsMixin:
@gather_metrics("container")
def container(
self,
*,
border: bool | None = None,
key: Key | None = None,
width: Width = "stretch",
height: Height = "content",
horizontal: bool = False,
horizontal_alignment: HorizontalAlignment = "left",
vertical_alignment: VerticalAlignment = "top",
gap: Gap | None = "small",
) -> DeltaGenerator:
"""Insert a multi-element container.
Inserts an invisible container into your app that can be used to hold
multiple elements. This allows you to, for example, insert multiple
elements into your app out of order.
To add elements to the returned container, you can use the ``with``
notation (preferred) or just call commands directly on the returned
object. See examples below.
Parameters
----------
border : bool or None
Whether to show a border around the container. If ``None`` (default), a
border is shown if the container is set to a fixed height and not
shown otherwise.
key : str or None
An optional string to give this container a stable identity.
Additionally, if ``key`` is provided, it will be used as CSS
class name prefixed with ``st-key-``.
width : "stretch", "content", or int
The width of the container. This can be one of the following:
- ``"stretch"`` (default): The width of the container matches the
width of the parent container.
- ``"content"``: The width of the container matches the width of
its content.
- An integer specifying the width in pixels: The container has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the container matches the width
of the parent container.
height : "content", "stretch", or int
The height of the container. This can be one of the following:
- ``"content"`` (default): The height of the container matches the
height of its content.
- ``"stretch"``: The height of the container matches the height of
its content or the height of the parent container, whichever is
larger. If the container is not in a parent container, the height
of the container matches the height of its content.
- An integer specifying the height in pixels: The container has a
fixed height. If the content is larger than the specified
height, scrolling is enabled.
.. note::
Use scrolling containers sparingly. If you use scrolling
containers, avoid heights that exceed 500 pixels. Otherwise,
the scroll surface of the container might cover the majority of
the screen on mobile devices, which makes it hard to scroll the
rest of the app.
horizontal : bool
Whether to use horizontal flexbox layout. If this is ``False``
(default), the container's elements are laid out vertically. If
this is ``True``, the container's elements are laid out
horizontally and will overflow to the next line if they don't fit
within the container's width.
horizontal_alignment : "left", "center", "right", or "distribute"
The horizontal alignment of the elements inside the container. This
can be one of the following:
- ``"left"`` (default): Elements are aligned to the left side of
the container.
- ``"center"``: Elements are horizontally centered inside the
container.
- ``"right"``: Elements are aligned to the right side of the
container.
- ``"distribute"``: Elements are distributed evenly in the
container. This increases the horizontal gap between elements to
fill the width of the container. A standalone element is aligned
to the left.
When ``horizontal`` is ``False``, ``"distribute"`` aligns the
elements the same as ``"left"``.
vertical_alignment : "top", "center", "bottom", or "distribute"
The vertical alignment of the elements inside the container. This
can be one of the following:
- ``"top"`` (default): Elements are aligned to the top of the
container.
- ``"center"``: Elements are vertically centered inside the
container.
- ``"bottom"``: Elements are aligned to the bottom of the
container.
- ``"distribute"``: Elements are distributed evenly in the
container. This increases the vertical gap between elements to
fill the height of the container. A standalone element is aligned
to the top.
When ``horizontal`` is ``True``, ``"distribute"`` aligns the
elements the same as ``"top"``.
gap : "small", "medium", "large", or None
The minimum gap size between the elements inside the container.
This can be one of the following:
- ``"small"`` (default): 1rem gap between the elements.
- ``"medium"``: 2rem gap between the elements.
- ``"large"``: 4rem gap between the elements.
- ``None``: No gap between the elements.
The rem unit is relative to the ``theme.baseFontSize``
configuration option.
The minimum gap applies to both the vertical and horizontal gaps
between the elements. Elements may have larger gaps in one
direction if you use a distributed horizontal alignment or fixed
height.
Examples
--------
**Example 1: Inserting elements using ``with`` notation**
You can use the ``with`` statement to insert any element into a
container.
>>> import streamlit as st
>>>
>>> with st.container():
... st.write("This is inside the container")
...
... # You can call any Streamlit command, including custom components:
... st.bar_chart(np.random.randn(50, 3))
>>>
>>> st.write("This is outside the container")
.. output::
https://doc-container1.streamlit.app/
height: 520px
**Example 2: Inserting elements out of order**
When you create a container, its position in the app remains fixed and
you can add elements to it at any time. This allows you to insert
elements out of order in your app. You can also write to the container
by calling commands directly on the container object.
>>> import streamlit as st
>>>
>>> container = st.container(border=True)
>>> container.write("This is inside the container")
>>> st.write("This is outside the container")
>>>
>>> container.write("This is inside too")
.. output::
https://doc-container2.streamlit.app/
height: 300px
**Example 3: Grid layout with columns and containers**
You can create a grid with a fixed number of elements per row by using
columns and containers.
>>> import streamlit as st
>>>
>>> row1 = st.columns(3)
>>> row2 = st.columns(3)
>>>
>>> for col in row1 + row2:
>>> tile = col.container(height=120)
>>> tile.title(":balloon:")
.. output::
https://doc-container3.streamlit.app/
height: 350px
**Example 4: Vertically scrolling container**
You can create a vertically scrolling container by setting a fixed
height.
>>> import streamlit as st
>>>
>>> long_text = "Lorem ipsum. " * 1000
>>>
>>> with st.container(height=300):
>>> st.markdown(long_text)
.. output::
https://doc-container4.streamlit.app/
height: 400px
**Example 5: Horizontal container**
You can create a row of widgets using a horizontal container. Use
``horizontal_alignment`` to specify the alignment of the elements.
>>> import streamlit as st
>>>
>>> flex = st.container(horizontal=True, horizontal_alignment="right")
>>>
>>> for card in range(3):
>>> flex.button(f"Button {card + 1}")
.. output::
https://doc-container5.streamlit.app/
height: 250px
"""
key = to_key(key)
block_proto = BlockProto()
block_proto.allow_empty = False
block_proto.flex_container.border = border or False
block_proto.flex_container.gap_config.gap_size = get_gap_size(
gap, "st.container"
)
validate_horizontal_alignment(horizontal_alignment)
validate_vertical_alignment(vertical_alignment)
if horizontal:
block_proto.flex_container.wrap = True
block_proto.flex_container.direction = (
BlockProto.FlexContainer.Direction.HORIZONTAL
)
block_proto.flex_container.justify = get_justify(horizontal_alignment)
block_proto.flex_container.align = get_align(vertical_alignment)
else:
block_proto.flex_container.wrap = False
block_proto.flex_container.direction = (
BlockProto.FlexContainer.Direction.VERTICAL
)
block_proto.flex_container.justify = get_justify(vertical_alignment)
block_proto.flex_container.align = get_align(horizontal_alignment)
validate_width(width, allow_content=True)
block_proto.width_config.CopyFrom(get_width_config(width))
if isinstance(height, int) or border:
block_proto.allow_empty = True
if border is not None:
block_proto.flex_container.border = border
elif isinstance(height, int):
block_proto.flex_container.border = True
else:
block_proto.flex_container.border = False
validate_height(height, allow_content=True)
block_proto.height_config.CopyFrom(get_height_config(height))
if key:
# At the moment, the ID is only used for extracting the
# key on the frontend and setting it as CSS class.
# There are plans to use the ID for other container features
# in the future. This might require including more container
# parameters in the ID calculation.
block_proto.id = compute_and_register_element_id(
"container", user_key=key, dg=None, key_as_main_identity=False
)
return self.dg._block(block_proto)
@gather_metrics("columns")
def columns(
self,
spec: SpecType,
*,
gap: Gap | None = "small",
vertical_alignment: Literal["top", "center", "bottom"] = "top",
border: bool = False,
width: WidthWithoutContent = "stretch",
) -> list[DeltaGenerator]:
"""Insert containers laid out as side-by-side columns.
Inserts a number of multi-element containers laid out side-by-side and
returns a list of container objects.
To add elements to the returned containers, you can use the ``with`` notation
(preferred) or just call methods directly on the returned object. See
examples below.
.. note::
To follow best design practices and maintain a good appearance on
all screen sizes, don't nest columns more than once.
Parameters
----------
spec : int or Iterable of numbers
Controls the number and width of columns to insert. Can be one of:
- An integer that specifies the number of columns. All columns have equal
width in this case.
- An Iterable of numbers (int or float) that specify the relative width of
each column. E.g. ``[0.7, 0.3]`` creates two columns where the first
one takes up 70% of the available with and the second one takes up 30%.
Or ``[1, 2, 3]`` creates three columns where the second one is two times
the width of the first one, and the third one is three times that width.
gap : "small", "medium", "large", or None
The size of the gap between the columns. This can be one of the
following:
- ``"small"`` (default): 1rem gap between the columns.
- ``"medium"``: 2rem gap between the columns.
- ``"large"``: 4rem gap between the columns.
- ``None``: No gap between the columns.
The rem unit is relative to the ``theme.baseFontSize``
configuration option.
vertical_alignment : "top", "center", or "bottom"
The vertical alignment of the content inside the columns. The
default is ``"top"``.
border : bool
Whether to show a border around the column containers. If this is
``False`` (default), no border is shown. If this is ``True``, a
border is shown around each column.
width : "stretch" or int
The width of the column group. This can be one of the following:
- ``"stretch"`` (default): The width of the column group matches the
width of the parent container.
- An integer specifying the width in pixels: The column group has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the column group matches the
width of the parent container.
Returns
-------
list of containers
A list of container objects.
Examples
--------
**Example 1: Use context management**
You can use the ``with`` statement to insert any element into a column:
>>> import streamlit as st
>>>
>>> col1, col2, col3 = st.columns(3)
>>>
>>> with col1:
... st.header("A cat")
... st.image("https://static.streamlit.io/examples/cat.jpg")
>>>
>>> with col2:
... st.header("A dog")
... st.image("https://static.streamlit.io/examples/dog.jpg")
>>>
>>> with col3:
... st.header("An owl")
... st.image("https://static.streamlit.io/examples/owl.jpg")
.. output::
https://doc-columns1.streamlit.app/
height: 620px
**Example 2: Use commands as container methods**
You can just call methods directly on the returned objects:
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = rng(0).standard_normal((10, 1))
>>> col1, col2 = st.columns([3, 1])
>>>
>>> col1.subheader("A wide column with a chart")
>>> col1.line_chart(df)
>>>
>>> col2.subheader("A narrow column with the data")
>>> col2.write(df)
.. output::
https://doc-columns2.streamlit.app/
height: 550px
**Example 3: Align widgets**
Use ``vertical_alignment="bottom"`` to align widgets.
>>> import streamlit as st
>>>
>>> left, middle, right = st.columns(3, vertical_alignment="bottom")
>>>
>>> left.text_input("Write something")
>>> middle.button("Click me", use_container_width=True)
>>> right.checkbox("Check me")
.. output::
https://doc-columns-bottom-widgets.streamlit.app/
height: 200px
**Example 4: Use vertical alignment to create grids**
Adjust vertical alignment to customize your grid layouts.
>>> import streamlit as st
>>>
>>> vertical_alignment = st.selectbox(
>>> "Vertical alignment", ["top", "center", "bottom"], index=2
>>> )
>>>
>>> left, middle, right = st.columns(3, vertical_alignment=vertical_alignment)
>>> left.image("https://static.streamlit.io/examples/cat.jpg")
>>> middle.image("https://static.streamlit.io/examples/dog.jpg")
>>> right.image("https://static.streamlit.io/examples/owl.jpg")
.. output::
https://doc-columns-vertical-alignment.streamlit.app/
height: 600px
**Example 5: Add borders**
Add borders to your columns instead of nested containers for consistent
heights.
>>> import streamlit as st
>>>
>>> left, middle, right = st.columns(3, border=True)
>>>
>>> left.markdown("Lorem ipsum " * 10)
>>> middle.markdown("Lorem ipsum " * 5)
>>> right.markdown("Lorem ipsum ")
.. output::
https://doc-columns-borders.streamlit.app/
height: 250px
"""
weights = spec
if isinstance(weights, int):
# If the user provided a single number, expand into equal weights.
# E.g. (1,) * 3 => (1, 1, 1)
# NOTE: A negative/zero spec will expand into an empty tuple.
weights = (1,) * weights
if len(weights) == 0 or any(weight <= 0 for weight in weights):
raise StreamlitInvalidColumnSpecError()
vertical_alignment_mapping: dict[
str, BlockProto.Column.VerticalAlignment.ValueType
] = {
"top": BlockProto.Column.VerticalAlignment.TOP,
"center": BlockProto.Column.VerticalAlignment.CENTER,
"bottom": BlockProto.Column.VerticalAlignment.BOTTOM,
}
if vertical_alignment not in vertical_alignment_mapping:
raise StreamlitInvalidVerticalAlignmentError(
vertical_alignment=vertical_alignment,
element_type="st.columns",
)
gap_size = get_gap_size(gap, "st.columns")
gap_config = GapConfig()
gap_config.gap_size = gap_size
def column_proto(normalized_weight: float) -> BlockProto:
col_proto = BlockProto()
col_proto.column.weight = normalized_weight
col_proto.column.gap_config.CopyFrom(gap_config)
col_proto.column.vertical_alignment = vertical_alignment_mapping[
vertical_alignment
]
col_proto.column.show_border = border
col_proto.allow_empty = True
return col_proto
block_proto = BlockProto()
block_proto.flex_container.direction = (
BlockProto.FlexContainer.Direction.HORIZONTAL
)
block_proto.flex_container.wrap = True
block_proto.flex_container.gap_config.CopyFrom(gap_config)
block_proto.flex_container.scale = 1
block_proto.flex_container.align = BlockProto.FlexContainer.Align.STRETCH
validate_width(width=width)
block_proto.width_config.CopyFrom(get_width_config(width=width))
row = self.dg._block(block_proto)
total_weight = sum(weights)
return [row._block(column_proto(w / total_weight)) for w in weights]
@gather_metrics("tabs")
def tabs(
self,
tabs: Sequence[str],
*,
width: WidthWithoutContent = "stretch",
default: str | None = None,
) -> Sequence[DeltaGenerator]:
r"""Insert containers separated into tabs.
Inserts a number of multi-element containers as tabs.
Tabs are a navigational element that allows users to easily
move between groups of related content.
To add elements to the returned containers, you can use the ``with`` notation
(preferred) or just call methods directly on the returned object. See
the examples below.
.. note::
All content within every tab is computed and sent to the frontend,
regardless of which tab is selected. Tabs do not currently support
conditional rendering. If you have a slow-loading tab, consider
using a widget like ``st.segmented_control`` to conditionally
render content instead.
Parameters
----------
tabs : list of str
Creates a tab for each string in the list. The first tab is selected
by default. The string is used as the name of the tab and can
optionally contain GitHub-flavored Markdown of the following types:
Bold, Italics, Strikethroughs, Inline Code, Links, and Images.
Images display like icons, with a max height equal to the font
height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
width : "stretch" or int
The width of the tab container. This can be one of the following:
- ``"stretch"`` (default): The width of the container matches the
width of the parent container.
- An integer specifying the width in pixels: The container has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the container matches the width
of the parent container.
default : str or None
The default tab to select. If this is ``None`` (default), the first
tab is selected. If this is a string, it must be one of the tab
labels. If two tabs have the same label as ``default``, the first
one is selected.
Returns
-------
list of containers
A list of container objects.
Examples
--------
*Example 1: Use context management*
You can use ``with`` notation to insert any element into a tab:
>>> import streamlit as st
>>>
>>> tab1, tab2, tab3 = st.tabs(["Cat", "Dog", "Owl"])
>>>
>>> with tab1:
... st.header("A cat")
... st.image("https://static.streamlit.io/examples/cat.jpg", width=200)
>>> with tab2:
... st.header("A dog")
... st.image("https://static.streamlit.io/examples/dog.jpg", width=200)
>>> with tab3:
... st.header("An owl")
... st.image("https://static.streamlit.io/examples/owl.jpg", width=200)
.. output::
https://doc-tabs1.streamlit.app/
height: 620px
*Example 2: Call methods directly*
You can call methods directly on the returned objects:
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = rng(0).standard_normal((10, 1))
>>>
>>> tab1, tab2 = st.tabs(["📈 Chart", "🗃 Data"])
>>>
>>> tab1.subheader("A tab with a chart")
>>> tab1.line_chart(df)
>>>
>>> tab2.subheader("A tab with the data")
>>> tab2.write(df)
.. output::
https://doc-tabs2.streamlit.app/
height: 700px
*Example 3: Set the default tab and style the tab labels*
Use the ``default`` parameter to set the default tab. You can also use
Markdown in the tab labels.
>>> import streamlit as st
>>>
>>> tab1, tab2, tab3 = st.tabs(
... [":cat: Cat", ":dog: Dog", ":rainbow[Owl]"], default=":rainbow[Owl]"
... )
>>>
>>> with tab1:
>>> st.header("A cat")
>>> st.image("https://static.streamlit.io/examples/cat.jpg", width=200)
>>> with tab2:
>>> st.header("A dog")
>>> st.image("https://static.streamlit.io/examples/dog.jpg", width=200)
>>> with tab3:
>>> st.header("An owl")
>>> st.image("https://static.streamlit.io/examples/owl.jpg", width=200)
.. output::
https://doc-tabs3.streamlit.app/
height: 620px
"""
if not tabs:
raise StreamlitAPIException(
"The input argument to st.tabs must contain at least one tab label."
)
if default and default not in tabs:
raise StreamlitAPIException(
f"The default tab '{default}' is not in the list of tabs."
)
if any(not isinstance(tab, str) for tab in tabs):
raise StreamlitAPIException(
"The tabs input list to st.tabs is only allowed to contain strings."
)
def tab_proto(label: str) -> BlockProto:
tab_proto = BlockProto()
tab_proto.tab.label = label
tab_proto.allow_empty = True
return tab_proto
block_proto = BlockProto()
block_proto.tab_container.SetInParent()
validate_width(width)
block_proto.width_config.CopyFrom(get_width_config(width))
default_index = tabs.index(default) if default else 0
block_proto.tab_container.default_tab_index = default_index
tab_container = self.dg._block(block_proto)
return tuple(tab_container._block(tab_proto(tab)) for tab in tabs)
@gather_metrics("expander")
def expander(
self,
label: str,
expanded: bool = False,
*,
icon: str | None = None,
width: WidthWithoutContent = "stretch",
) -> DeltaGenerator:
r"""Insert a multi-element container that can be expanded/collapsed.
Inserts a container into your app that can be used to hold multiple elements
and can be expanded or collapsed by the user. When collapsed, all that is
visible is the provided label.
To add elements to the returned container, you can use the ``with`` notation
(preferred) or just call methods directly on the returned object. See
examples below.
.. note::
All content within the expander is computed and sent to the
frontend, even if the expander is closed.
To follow best design practices and maintain a good appearance on
all screen sizes, don't nest expanders.
Parameters
----------
label : str
A string to use as the header for the expander. The label can optionally
contain GitHub-flavored Markdown of the following types: Bold, Italics,
Strikethroughs, Inline Code, Links, and Images. Images display like
icons, with a max height equal to the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
expanded : bool
If True, initializes the expander in "expanded" state. Defaults to
False (collapsed).
icon : str, None
An optional emoji or icon to display next to the expander label. If ``icon``
is ``None`` (default), no icon is displayed. If ``icon`` is a
string, the following options are valid:
- A single-character emoji. For example, you can set ``icon="🚨"``
or ``icon="🔥"``. Emoji short codes are not supported.
- An icon from the Material Symbols library (rounded style) in the
format ``":material/icon_name:"`` where "icon_name" is the name
of the icon in snake case.
For example, ``icon=":material/thumb_up:"`` will display the
Thumb Up icon. Find additional icons in the `Material Symbols \
<https://fonts.google.com/icons?icon.set=Material+Symbols&icon.style=Rounded>`_
font library.
- ``"spinner"``: Displays a spinner as an icon.
width : "stretch" or int
The width of the expander container. This can be one of the following:
- ``"stretch"`` (default): The width of the container matches the
width of the parent container.
- An integer specifying the width in pixels: The container has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the container matches the width
of the parent container.
Examples
--------
You can use the ``with`` notation to insert any element into an expander
>>> import streamlit as st
>>>
>>> st.bar_chart({"data": [1, 5, 2, 6, 2, 1]})
>>>
>>> with st.expander("See explanation"):
... st.write('''
... The chart above shows some numbers I picked for you.
... I rolled actual dice for these, so they're *guaranteed* to
... be random.
... ''')
... st.image("https://static.streamlit.io/examples/dice.jpg")
.. output::
https://doc-expander.streamlit.app/
height: 750px
Or you can just call methods directly on the returned objects:
>>> import streamlit as st
>>>
>>> st.bar_chart({"data": [1, 5, 2, 6, 2, 1]})
>>>
>>> expander = st.expander("See explanation")
>>> expander.write('''
... The chart above shows some numbers I picked for you.
... I rolled actual dice for these, so they're *guaranteed* to
... be random.
... ''')
>>> expander.image("https://static.streamlit.io/examples/dice.jpg")
.. output::
https://doc-expander.streamlit.app/
height: 750px
"""
if label is None:
raise StreamlitAPIException("A label is required for an expander")
expandable_proto = BlockProto.Expandable()
expandable_proto.expanded = expanded
expandable_proto.label = label
if icon is not None:
expandable_proto.icon = validate_icon_or_emoji(icon)
block_proto = BlockProto()
block_proto.allow_empty = True
block_proto.expandable.CopyFrom(expandable_proto)
validate_width(width)
block_proto.width_config.CopyFrom(get_width_config(width))
return self.dg._block(block_proto=block_proto)
@gather_metrics("popover")
def popover(
self,
label: str,
*,
type: Literal["primary", "secondary", "tertiary"] = "secondary",
help: str | None = None,
icon: str | None = None,
disabled: bool = False,
use_container_width: bool | None = None,
width: Width = "content",
) -> DeltaGenerator:
r"""Insert a popover container.
Inserts a multi-element container as a popover. It consists of a button-like
element and a container that opens when the button is clicked.
Opening and closing the popover will not trigger a rerun. Interacting
with widgets inside of an open popover will rerun the app while keeping
the popover open. Clicking outside of the popover will close it.
To add elements to the returned container, you can use the "with"
notation (preferred) or just call methods directly on the returned object.
See examples below.
.. note::
To follow best design practices, don't nest popovers.
Parameters
----------
label : str
The label of the button that opens the popover container.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
help : str or None
A tooltip that gets displayed when the popover button is hovered
over. If this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
type : "primary", "secondary", or "tertiary"
An optional string that specifies the button type. This can be one
of the following:
- ``"primary"``: The button's background is the app's primary color
for additional emphasis.
- ``"secondary"`` (default): The button's background coordinates
with the app's background color for normal emphasis.
- ``"tertiary"``: The button is plain text without a border or
background for subtlety.
icon : str
An optional emoji or icon to display next to the button label. If ``icon``
is ``None`` (default), no icon is displayed. If ``icon`` is a
string, the following options are valid:
- A single-character emoji. For example, you can set ``icon="🚨"``
or ``icon="🔥"``. Emoji short codes are not supported.
- An icon from the Material Symbols library (rounded style) in the
format ``":material/icon_name:"`` where "icon_name" is the name
of the icon in snake case.
For example, ``icon=":material/thumb_up:"`` will display the
Thumb Up icon. Find additional icons in the `Material Symbols \
<https://fonts.google.com/icons?icon.set=Material+Symbols&icon.style=Rounded>`_
font library.
- ``"spinner"``: Displays a spinner as an icon.
disabled : bool
An optional boolean that disables the popover button if set to
``True``. The default is ``False``.
use_container_width : bool
Whether to expand the button's width to fill its parent container.
If ``use_container_width`` is ``False`` (default), Streamlit sizes
the button to fit its content. If ``use_container_width`` is
``True``, the width of the button matches its parent container.
In both cases, if the content of the button is wider than the
parent container, the content will line wrap.
The popover container's minimum width matches the width of its
button. The popover container may be wider than its button to fit
the container's content.
.. deprecated::
``use_container_width`` is deprecated and will be removed in a
future release. For ``use_container_width=True``, use
``width="stretch"``. For ``use_container_width=False``, use
``width="content"``.
width : int, "stretch", or "content"
The width of the button. This can be one of the following:
- ``"content"`` (default): The width of the button matches the
width of its content, but doesn't exceed the width of the parent
container.
- ``"stretch"``: The width of the button matches the width of the
parent container.
- An integer specifying the width in pixels: The button has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the button matches the width
of the parent container.
The popover container's minimum width matches the width of its
button. The popover container may be wider than its button to fit
the container's contents.
Examples
--------
You can use the ``with`` notation to insert any element into a popover:
>>> import streamlit as st
>>>
>>> with st.popover("Open popover"):
>>> st.markdown("Hello World 👋")
>>> name = st.text_input("What's your name?")
>>>
>>> st.write("Your name:", name)
.. output::
https://doc-popover.streamlit.app/
height: 400px
Or you can just call methods directly on the returned objects:
>>> import streamlit as st
>>>
>>> popover = st.popover("Filter items")
>>> red = popover.checkbox("Show red items.", True)
>>> blue = popover.checkbox("Show blue items.", True)
>>>
>>> if red:
... st.write(":red[This is a red item.]")
>>> if blue:
... st.write(":blue[This is a blue item.]")
.. output::
https://doc-popover2.streamlit.app/
height: 400px
"""
if label is None:
raise StreamlitAPIException("A label is required for a popover")
if use_container_width is not None:
width = "stretch" if use_container_width else "content"
# Checks whether the entered button type is one of the allowed options
if type not in ["primary", "secondary", "tertiary"]:
raise StreamlitAPIException(
'The type argument to st.popover must be "primary", "secondary", or "tertiary". '
f'\nThe argument passed was "{type}".'
)
popover_proto = BlockProto.Popover()
popover_proto.label = label
popover_proto.disabled = disabled
popover_proto.type = type
if help:
popover_proto.help = str(help)
if icon is not None:
popover_proto.icon = validate_icon_or_emoji(icon)
block_proto = BlockProto()
block_proto.allow_empty = True
block_proto.popover.CopyFrom(popover_proto)
validate_width(width, allow_content=True)
block_proto.width_config.CopyFrom(get_width_config(width))
return self.dg._block(block_proto=block_proto)
@gather_metrics("status")
def status(
self,
label: str,
*,
expanded: bool = False,
state: Literal["running", "complete", "error"] = "running",
width: WidthWithoutContent = "stretch",
) -> StatusContainer:
r"""Insert a status container to display output from long-running tasks.
Inserts a container into your app that is typically used to show the status and
details of a process or task. The container can hold multiple elements and can
be expanded or collapsed by the user similar to ``st.expander``.
When collapsed, all that is visible is the status icon and label.
The label, state, and expanded state can all be updated by calling ``.update()``
on the returned object. To add elements to the returned container, you can
use ``with`` notation (preferred) or just call methods directly on the returned
object.
By default, ``st.status()`` initializes in the "running" state. When called using
``with`` notation, it automatically updates to the "complete" state at the end
of the "with" block. See examples below for more details.
.. note::
All content within the status container is computed and sent to the
frontend, even if the status container is closed.
To follow best design practices and maintain a good appearance on
all screen sizes, don't nest status containers.
Parameters
----------
label : str
The initial label of the status container. The label can optionally
contain GitHub-flavored Markdown of the following types: Bold, Italics,
Strikethroughs, Inline Code, Links, and Images. Images display like
icons, with a max height equal to the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
expanded : bool
If True, initializes the status container in "expanded" state. Defaults to
False (collapsed).
state : "running", "complete", or "error"
The initial state of the status container which determines which icon is
shown:
- ``running`` (default): A spinner icon is shown.
- ``complete``: A checkmark icon is shown.
- ``error``: An error icon is shown.
width : "stretch" or int
The width of the status container. This can be one of the following:
- ``"stretch"`` (default): The width of the container matches the
width of the parent container.
- An integer specifying the width in pixels: The container has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the container matches the width
of the parent container.
Returns
-------
StatusContainer
A mutable status container that can hold multiple elements. The label, state,
and expanded state can be updated after creation via ``.update()``.
Examples
--------
You can use the ``with`` notation to insert any element into an status container:
>>> import time
>>> import streamlit as st
>>>
>>> with st.status("Downloading data..."):
... st.write("Searching for data...")
... time.sleep(2)
... st.write("Found URL.")
... time.sleep(1)
... st.write("Downloading data...")
... time.sleep(1)
>>>
>>> st.button("Rerun")
.. output::
https://doc-status.streamlit.app/
height: 300px
You can also use ``.update()`` on the container to change the label, state,
or expanded state:
>>> import time
>>> import streamlit as st
>>>
>>> with st.status("Downloading data...", expanded=True) as status:
... st.write("Searching for data...")
... time.sleep(2)
... st.write("Found URL.")
... time.sleep(1)
... st.write("Downloading data...")
... time.sleep(1)
... status.update(
... label="Download complete!", state="complete", expanded=False
... )
>>>
>>> st.button("Rerun")
.. output::
https://doc-status-update.streamlit.app/
height: 300px
"""
return get_dg_singleton_instance().status_container_cls._create(
self.dg, label, expanded=expanded, state=state, width=width
)
def _dialog(
self,
title: str,
*,
dismissible: bool = True,
width: Literal["small", "large", "medium"] = "small",
on_dismiss: Literal["ignore", "rerun"] | WidgetCallback = "ignore",
) -> Dialog:
"""Inserts the dialog container.
Marked as internal because it is used by the dialog_decorator and is not supposed to be used directly.
The dialog_decorator also has a more descriptive docstring since it is user-facing.
"""
return get_dg_singleton_instance().dialog_container_cls._create(
self.dg, title, dismissible=dismissible, width=width, on_dismiss=on_dismiss
)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/doc_string.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
"""Allows us to create and absorb changes (aka Deltas) to elements."""
from __future__ import annotations
import ast
import contextlib
import inspect
import re
import types
from typing import TYPE_CHECKING, Any, Final, cast
import streamlit
from streamlit.elements.lib.layout_utils import LayoutConfig, validate_width
from streamlit.proto.DocString_pb2 import DocString as DocStringProto
from streamlit.proto.DocString_pb2 import Member as MemberProto
from streamlit.runtime.caching.cache_utils import CachedFunc
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner.script_runner import (
__file__ as SCRIPTRUNNER_FILENAME, # noqa: N812
)
from streamlit.runtime.secrets import Secrets
from streamlit.string_util import is_mem_address_str
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
from streamlit.elements.lib.layout_utils import WidthWithoutContent
CONFUSING_STREAMLIT_SIG_PREFIXES: Final = ("(element, ",)
class HelpMixin:
@gather_metrics("help")
def help(
self, obj: Any = streamlit, *, width: WidthWithoutContent = "stretch"
) -> DeltaGenerator:
"""Display help and other information for a given object.
Depending on the type of object that is passed in, this displays the
object's name, type, value, signature, docstring, and member variables,
methods — as well as the values/docstring of members and methods.
Parameters
----------
obj : any
The object whose information should be displayed. If left
unspecified, this call will display help for Streamlit itself.
width : "stretch" or int
The width of the help element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
Example
-------
Don't remember how to initialize a dataframe? Try this:
>>> import streamlit as st
>>> import pandas
>>>
>>> st.help(pandas.DataFrame)
.. output::
https://doc-string.streamlit.app/
height: 700px
Want to quickly check what data type is output by a certain function?
Try:
>>> import streamlit as st
>>>
>>> x = my_poorly_documented_function()
>>> st.help(x)
Want to quickly inspect an object? No sweat:
>>> class Dog:
>>> '''A typical dog.'''
>>>
>>> def __init__(self, breed, color):
>>> self.breed = breed
>>> self.color = color
>>>
>>> def bark(self):
>>> return 'Woof!'
>>>
>>>
>>> fido = Dog("poodle", "white")
>>>
>>> st.help(fido)
.. output::
https://doc-string1.streamlit.app/
height: 300px
And if you're using Magic, you can get help for functions, classes,
and modules without even typing ``st.help``:
>>> import streamlit as st
>>> import pandas
>>>
>>> # Get help for Pandas read_csv:
>>> pandas.read_csv
>>>
>>> # Get help for Streamlit itself:
>>> st
.. output::
https://doc-string2.streamlit.app/
height: 700px
"""
doc_string_proto = DocStringProto()
validate_width(width, allow_content=False)
layout_config = LayoutConfig(width=width)
_marshall(doc_string_proto, obj)
return self.dg._enqueue(
"doc_string", doc_string_proto, layout_config=layout_config
)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
def _marshall(doc_string_proto: DocStringProto, obj: Any) -> None:
"""Construct a DocString object.
See DeltaGenerator.help for docs.
"""
var_name = _get_variable_name()
if var_name is not None:
doc_string_proto.name = var_name
obj_type = _get_type_as_str(obj)
doc_string_proto.type = obj_type
obj_docs = _get_docstring(obj)
if obj_docs is not None:
doc_string_proto.doc_string = obj_docs
obj_value = _get_value(obj, var_name)
if obj_value is not None:
doc_string_proto.value = obj_value
doc_string_proto.members.extend(_get_members(obj))
def _get_name(obj: object) -> str | None:
# Try to get the fully-qualified name of the object.
# For example: st.help(bar.Baz(123))
# The name is bar.Baz
name = getattr(obj, "__qualname__", None)
if name:
return cast("str", name)
# Try to get the name of the object.
# For example: st.help(bar.Baz(123))
# The name is Baz
return cast("str | None", getattr(obj, "__name__", None))
def _get_module(obj: object) -> str | None:
return getattr(obj, "__module__", None)
def _get_signature(obj: object) -> str | None:
if not inspect.isclass(obj) and not callable(obj):
return None
sig = ""
try:
sig = str(inspect.signature(obj))
except ValueError:
sig = "(...)"
except TypeError:
return None
is_delta_gen = False
with contextlib.suppress(AttributeError):
is_delta_gen = obj.__module__ == "streamlit.delta_generator"
# Functions such as numpy.minimum don't have a __module__ attribute,
# since we're only using it to check if its a DeltaGenerator, its ok
# to continue
if is_delta_gen:
for prefix in CONFUSING_STREAMLIT_SIG_PREFIXES:
if sig.startswith(prefix):
sig = sig.replace(prefix, "(")
break
return sig
def _get_docstring(obj: object) -> str | None:
doc_string = inspect.getdoc(obj)
# Sometimes an object has no docstring, but the object's type does.
# If that's the case here, use the type's docstring.
# For objects where type is "type" we do not print the docs (e.g. int).
# We also do not print the docs for functions and methods if the docstring is empty.
# We treat CachedFunc objects in the same way as functions.
if doc_string is None:
obj_type = type(obj)
if (
obj_type is not type
and obj_type is not types.ModuleType
and not inspect.isfunction(obj)
and not inspect.ismethod(obj)
and obj_type is not CachedFunc
):
doc_string = inspect.getdoc(obj_type)
if doc_string:
return doc_string.strip()
return None
def _get_variable_name() -> str | None:
"""Try to get the name of the variable in the current line, as set by the user.
For example:
foo = bar.Baz(123)
st.help(foo)
The name is "foo"
"""
code = _get_current_line_of_code_as_str()
if code is None:
return None
return _get_variable_name_from_code_str(code)
def _get_variable_name_from_code_str(code: str) -> str | None:
tree = ast.parse(code)
# Example:
#
# > tree = Module(
# > body=[
# > Expr(
# > value=Call(
# > args=[
# > Name(id='the variable name')
# > ],
# > keywords=[
# > ???
# > ],
# > )
# > )
# > ]
# > )
# Check if this is an magic call (i.e. it's not st.help or st.write).
# If that's the case, just clean it up and return it.
if not _is_stcommand(tree, command_name="help") and not _is_stcommand(
tree, command_name="write"
):
# A common pattern is to add "," at the end of a magic command to make it print.
# This removes that final ",", so it looks nicer.
return code.removesuffix(",")
arg_node = _get_stcommand_arg(tree)
# If st.help() is called without an argument, return no variable name.
if not arg_node:
return None
# If walrus, get name.
# E.g. st.help(foo := 123) should give you "foo".
if type(arg_node) is ast.NamedExpr:
# This next "if" will always be true, but need to add this for the type-checking test to
# pass.
if type(arg_node.target) is ast.Name:
return arg_node.target.id
# If constant, there's no variable name.
# E.g. st.help("foo") or st.help(123) should give you None.
elif type(arg_node) is ast.Constant:
return None
# Otherwise, return whatever is inside st.help(<-- here -->)
# But, if multiline, only return the first line.
code_lines = code.split("\n")
is_multiline = len(code_lines) > 1
start_offset = arg_node.col_offset
if is_multiline:
first_lineno = arg_node.lineno - 1 # Lines are 1-indexed!
first_line = code_lines[first_lineno]
end_offset = None
else:
first_line = code_lines[0]
end_offset = getattr(arg_node, "end_col_offset", -1)
return first_line[start_offset:end_offset]
_NEWLINES = re.compile(r"[\n\r]+")
def _get_current_line_of_code_as_str() -> str | None:
scriptrunner_frame = _get_scriptrunner_frame()
if scriptrunner_frame is None:
# If there's no ScriptRunner frame, something weird is going on. This
# can happen when the script is executed with `python myscript.py`.
# Either way, let's bail out nicely just in case there's some valid
# edge case where this is OK.
return None
code_context = scriptrunner_frame.code_context
if not code_context:
# Sometimes a frame has no code_context. This can happen inside certain exec() calls, for
# example. If this happens, we can't determine the variable name. Just return.
# For the background on why exec() doesn't produce code_context, see
# https://stackoverflow.com/a/12072941
return None
code_as_string = "".join(code_context)
return re.sub(_NEWLINES, "", code_as_string.strip())
def _get_scriptrunner_frame() -> inspect.FrameInfo | None:
prev_frame = None
scriptrunner_frame = None
# Look back in call stack to get the variable name passed into st.help().
# The frame *before* the ScriptRunner frame is the correct one.
# IMPORTANT: This will change if we refactor the code. But hopefully our tests will catch the
# issue and we'll fix it before it lands upstream!
for frame in inspect.stack():
# Check if this is running inside a funny "exec()" block that won't provide the info we
# need. If so, just quit.
if frame.code_context is None:
return None
if frame.filename == SCRIPTRUNNER_FILENAME:
scriptrunner_frame = prev_frame
break
prev_frame = frame
return scriptrunner_frame
def _is_stcommand(tree: Any, command_name: str) -> bool:
"""Checks whether the AST in tree is a call for command_name."""
root_node = tree.body[0].value
if not isinstance(root_node, ast.Call):
return False
return (
# st call called without module. E.g. "help()"
getattr(root_node.func, "id", None) == command_name
or
# st call called with module. E.g. "foo.help()" (where usually "foo" is "st")
getattr(root_node.func, "attr", None) == command_name
)
def _get_stcommand_arg(tree: ast.Module) -> ast.expr | None:
"""Gets the argument node for the st command in tree (AST)."""
root_node = tree.body[0].value # type: ignore
if root_node.args:
return cast("ast.expr", root_node.args[0])
return None
def _get_type_as_str(obj: object) -> str:
if inspect.isclass(obj):
return "class"
return str(type(obj).__name__)
def _get_first_line(text: str) -> str:
if not text:
return ""
left, _, _ = text.partition("\n")
return left
def _get_weight(value: Any) -> int:
if inspect.ismodule(value):
return 3
if inspect.isclass(value):
return 2
if callable(value):
return 1
return 0
def _get_value(obj: object, var_name: str | None) -> str | None:
obj_value = _get_human_readable_value(obj)
if obj_value is not None:
return obj_value
# If there's no human-readable value, it's some complex object.
# So let's provide other info about it.
name = _get_name(obj)
if name:
name_obj = obj
else:
# If the object itself doesn't have a name, then it's probably an instance
# of some class Foo. So let's show info about Foo in the value slot.
name_obj = type(obj)
name = _get_name(name_obj)
module = _get_module(name_obj)
sig = _get_signature(name_obj) or ""
if name:
obj_value = f"{module}.{name}{sig}" if module else f"{name}{sig}"
if obj_value == var_name:
# No need to repeat the same info.
# For example: st.help(re) shouldn't show "re module re", just "re module".
obj_value = None
return obj_value
def _get_human_readable_value(value: Any) -> str | None:
if isinstance(value, Secrets):
# Don't want to read secrets.toml because that will show a warning if there's no
# secrets.toml file.
return None
if inspect.isclass(value) or inspect.ismodule(value) or callable(value):
return None
value_str = repr(value)
if isinstance(value, str):
# Special-case strings as human-readable because they're allowed to look like
# "<foo blarg at 0x15ee6f9a0>".
return _shorten(value_str)
if is_mem_address_str(value_str):
# If value_str looks like "<foo blarg at 0x15ee6f9a0>" it's not human readable.
return None
return _shorten(value_str)
def _shorten(s: str, length: int = 300) -> str:
s = s.strip()
return s[:length] + "..." if len(s) > length else s
def _is_computed_property(obj: object, attr_name: str) -> bool:
obj_class = getattr(obj, "__class__", None)
if not obj_class:
return False
# Go through superclasses in order of inheritance (mro) to see if any of them have an
# attribute called attr_name. If so, check if it's a @property.
for parent_class in inspect.getmro(obj_class):
class_attr = getattr(parent_class, attr_name, None)
if class_attr is None:
continue
# If is property, return it.
if isinstance(class_attr, property) or inspect.isgetsetdescriptor(class_attr):
return True
return False
def _get_members(obj: object) -> list[MemberProto]:
members_for_sorting = []
for attr_name in dir(obj):
if attr_name.startswith("_"):
continue
try:
is_computed_value = _is_computed_property(obj, attr_name)
if is_computed_value:
parent_attr = getattr(obj.__class__, attr_name)
member_type = "property"
weight = 0
member_docs = _get_docstring(parent_attr)
member_value = None
else:
attr_value = getattr(obj, attr_name)
weight = _get_weight(attr_value)
human_readable_value = _get_human_readable_value(attr_value)
member_type = _get_type_as_str(attr_value)
if human_readable_value is None:
member_docs = _get_docstring(attr_value)
member_value = None
else:
member_docs = None
member_value = human_readable_value
except AttributeError:
# If there's an AttributeError, we can just skip it.
# This can happen when members are exposed with `dir()`
# but are conditionally unavailable.
continue
if member_type == "module":
# Don't pollute the output with all imported modules.
continue
member = MemberProto()
member.name = attr_name
member.type = member_type
if member_docs is not None:
member.doc_string = _get_first_line(member_docs)
if member_value is not None:
member.value = member_value
members_for_sorting.append((weight, member))
if members_for_sorting:
sorted_members = sorted(members_for_sorting, key=lambda x: (x[0], x[1].name))
return [m for _, m in sorted_members]
return []
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/balloons.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from typing import TYPE_CHECKING, cast
from streamlit.proto.Balloons_pb2 import Balloons as BalloonsProto
from streamlit.runtime.metrics_util import gather_metrics
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
class BalloonsMixin:
@gather_metrics("balloons")
def balloons(self) -> DeltaGenerator:
"""Draw celebratory balloons.
Example
-------
>>> import streamlit as st
>>>
>>> st.balloons()
...then watch your app and get ready for a celebration!
"""
balloons_proto = BalloonsProto()
balloons_proto.show = True
return self.dg._enqueue("balloons", balloons_proto)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/pyplot.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
"""Streamlit support for Matplotlib PyPlot charts."""
from __future__ import annotations
import io
from typing import TYPE_CHECKING, Any, cast
from streamlit.deprecation_util import (
make_deprecated_name_warning,
show_deprecation_warning,
)
from streamlit.elements.lib.image_utils import marshall_images
from streamlit.elements.lib.layout_utils import LayoutConfig, Width, validate_width
from streamlit.proto.Image_pb2 import ImageList as ImageListProto
from streamlit.runtime.metrics_util import gather_metrics
if TYPE_CHECKING:
from matplotlib.figure import Figure
from streamlit.delta_generator import DeltaGenerator
class PyplotMixin:
@gather_metrics("pyplot")
def pyplot(
self,
fig: Figure | None = None,
clear_figure: bool | None = None,
*,
width: Width = "stretch",
use_container_width: bool | None = None,
**kwargs: Any,
) -> DeltaGenerator:
"""Display a matplotlib.pyplot figure.
.. Important::
You must install ``matplotlib>=3.0.0`` to use this command. You can
install all charting dependencies (except Bokeh) as an extra with
Streamlit:
.. code-block:: shell
pip install streamlit[charts]
Parameters
----------
fig : Matplotlib Figure
The Matplotlib ``Figure`` object to render. See
https://matplotlib.org/stable/gallery/index.html for examples.
.. note::
When this argument isn't specified, this function will render the global
Matplotlib figure object. However, this feature is deprecated and
will be removed in a later version.
clear_figure : bool
If True, the figure will be cleared after being rendered.
If False, the figure will not be cleared after being rendered.
If left unspecified, we pick a default based on the value of ``fig``.
- If ``fig`` is set, defaults to ``False``.
- If ``fig`` is not set, defaults to ``True``. This simulates Jupyter's
approach to matplotlib rendering.
width : "stretch", "content", or int
The width of the chart element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- ``"content"``: The width of the element matches the
width of its content, but doesn't exceed the width of the parent
container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
use_container_width : bool
Whether to override the figure's native width with the width of
the parent container. If ``use_container_width`` is ``True``
(default), Streamlit sets the width of the figure to match the
width of the parent container. If ``use_container_width`` is
``False``, Streamlit sets the width of the chart to fit its
contents according to the plotting library, up to the width of the
parent container.
.. deprecated::
``use_container_width`` is deprecated and will be removed in a
future release. For ``use_container_width=True``, use
``width="stretch"``. For ``use_container_width=False``, use
``width="content"``.
**kwargs : any
Arguments to pass to Matplotlib's savefig function.
Example
-------
>>> import matplotlib.pyplot as plt
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> arr = rng(0).normal(1, 1, size=100)
>>> fig, ax = plt.subplots()
>>> ax.hist(arr, bins=20)
>>>
>>> st.pyplot(fig)
.. output::
https://doc-pyplot.streamlit.app/
height: 630px
Matplotlib supports several types of "backends". If you're getting an
error using Matplotlib with Streamlit, try setting your backend to "TkAgg"::
echo "backend: TkAgg" >> ~/.matplotlib/matplotlibrc
For more information, see https://matplotlib.org/faq/usage_faq.html.
"""
if use_container_width is not None:
show_deprecation_warning(
make_deprecated_name_warning(
"use_container_width",
"width",
"2025-12-31",
"For `use_container_width=True`, use `width='stretch'`. "
"For `use_container_width=False`, use `width='content'`.",
include_st_prefix=False,
),
show_in_browser=False,
)
width = "stretch" if use_container_width else "content"
if not fig:
show_deprecation_warning("""
Calling `st.pyplot()` without providing a figure argument has been deprecated
and will be removed in a later version as it requires the use of Matplotlib's
global figure object, which is not thread-safe.
To future-proof this code, you should pass in a figure as shown below:
```python
fig, ax = plt.subplots()
ax.scatter([1, 2, 3], [1, 2, 3])
# other plotting actions...
st.pyplot(fig)
```
If you have a specific use case that requires this functionality, please let us
know via [issue on Github](https://github.com/streamlit/streamlit/issues).
""")
validate_width(width, allow_content=True)
layout_config = LayoutConfig(width=width)
image_list_proto = ImageListProto()
marshall(
self.dg._get_delta_path_str(),
image_list_proto,
layout_config,
fig,
clear_figure,
**kwargs,
)
return self.dg._enqueue("imgs", image_list_proto, layout_config=layout_config)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
def marshall(
coordinates: str,
image_list_proto: ImageListProto,
layout_config: LayoutConfig,
fig: Figure | None = None,
clear_figure: bool | None = True,
**kwargs: Any,
) -> None:
try:
import matplotlib.pyplot as plt
plt.ioff()
except ImportError:
raise ImportError("pyplot() command requires matplotlib")
# You can call .savefig() on a Figure object or directly on the pyplot
# module, in which case you're doing it to the latest Figure.
if not fig:
if clear_figure is None:
clear_figure = True
fig = cast("Figure", plt)
# Normally, dpi is set to 'figure', and the figure's dpi is set to 100.
# So here we pick double of that to make things look good in a high
# DPI display.
options = {"bbox_inches": "tight", "dpi": 200, "format": "png"}
# If some options are passed in from kwargs then replace the values in
# options with the ones from kwargs
options = {a: kwargs.get(a, b) for a, b in options.items()}
# Merge options back into kwargs.
kwargs.update(options)
image = io.BytesIO()
fig.savefig(image, **kwargs)
marshall_images(
coordinates=coordinates,
image=image,
caption=None,
layout_config=layout_config,
proto_imgs=image_list_proto,
clamp=False,
channels="RGB",
output_format="PNG",
)
# Clear the figure after rendering it. This means that subsequent
# plt calls will be starting fresh.
if clear_figure:
fig.clf()
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/dialog_decorator.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from collections.abc import Callable
from functools import wraps
from typing import TYPE_CHECKING, Any, Literal, TypeVar, cast, overload
from streamlit.delta_generator_singletons import (
get_dg_singleton_instance,
get_last_dg_added_to_context_stack,
)
from streamlit.errors import StreamlitAPIException
from streamlit.runtime.fragment import _fragment
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.type_util import get_object_name
if TYPE_CHECKING:
from streamlit.elements.lib.dialog import DialogWidth
from streamlit.runtime.state import WidgetCallback
def _assert_no_nested_dialogs() -> None:
"""Check the current stack for existing DeltaGenerator's of type 'dialog'.
Note that the check like this only works when Dialog is called as a context manager,
as this populates the dg_stack in delta_generator correctly.
This does not detect the edge case in which someone calls, for example,
`with st.sidebar` inside of a dialog function and opens a dialog in there, as
`with st.sidebar` pushes the new DeltaGenerator to the stack. In order to check for
that edge case, we could try to check all DeltaGenerators in the stack, and not only
the last one. Since we deem this to be an edge case, we lean towards simplicity
here.
Raises
------
StreamlitAPIException
Raised if the user tries to nest dialogs inside of each other.
"""
last_dg_in_current_context = get_last_dg_added_to_context_stack()
if last_dg_in_current_context and "dialog" in set(
last_dg_in_current_context._ancestor_block_types
):
raise StreamlitAPIException("Dialogs may not be nested inside other dialogs.")
F = TypeVar("F", bound=Callable[..., Any])
def _dialog_decorator(
non_optional_func: F,
title: str,
*,
width: DialogWidth = "small",
dismissible: bool = True,
on_dismiss: Literal["ignore", "rerun"] | WidgetCallback = "ignore",
) -> F:
if title is None or title == "":
raise StreamlitAPIException(
"A non-empty `title` argument has to be provided for dialogs, for example "
'`@st.dialog("Example Title")`.'
)
@wraps(non_optional_func)
def wrap(*args: Any, **kwargs: Any) -> None:
_assert_no_nested_dialogs()
# Call the Dialog on the event_dg because it lives outside of the normal
# Streamlit UI flow. For example, if it is called from the sidebar, it should
# not inherit the sidebar theming.
dialog = get_dg_singleton_instance().event_dg._dialog(
title=title, dismissible=dismissible, width=width, on_dismiss=on_dismiss
)
dialog.open()
def dialog_content() -> None:
# if the dialog should be closed, st.rerun() has to be called
# (same behavior as with st.fragment)
_ = non_optional_func(*args, **kwargs)
# the fragment decorator has multiple return types so that you can pass
# arguments to it. Here we know the return type, so we cast
fragmented_dialog_content = cast(
"Callable[[], None]",
_fragment(
dialog_content, additional_hash_info=get_object_name(non_optional_func)
),
)
with dialog:
fragmented_dialog_content()
return
return cast("F", wrap)
@overload
def dialog_decorator(
title: str,
*,
width: DialogWidth = "small",
dismissible: bool = True,
on_dismiss: Literal["ignore", "rerun"] | WidgetCallback = "ignore",
) -> Callable[[F], F]: ...
# 'title' can be a function since `dialog_decorator` is a decorator.
# We just call it 'title' here though to make the user-doc more friendly as
# we want the user to pass a title, not a function. The user is supposed to
# call it like @st.dialog("my_title") , which makes 'title' a positional arg, hence
# this 'trick'. The overload is required to have a good type hint for the decorated
# function args.
@overload
def dialog_decorator(
title: F,
*,
width: DialogWidth = "small",
dismissible: bool = True,
on_dismiss: Literal["ignore", "rerun"] | WidgetCallback = "ignore",
) -> F: ...
@gather_metrics("dialog")
def dialog_decorator(
title: F | str,
*,
width: DialogWidth = "small",
dismissible: bool = True,
on_dismiss: Literal["ignore", "rerun"] | WidgetCallback = "ignore",
) -> F | Callable[[F], F]:
r"""Function decorator to create a modal dialog.
A function decorated with ``@st.dialog`` becomes a dialog
function. When you call a dialog function, Streamlit inserts a modal dialog
into your app. Streamlit element commands called within the dialog function
render inside the modal dialog.
The dialog function can accept arguments that can be passed when it is
called. Any values from the dialog that need to be accessed from the wider
app should generally be stored in Session State.
If a dialog is dismissible, a user can dismiss it by clicking outside of
it, clicking the "**X**" in its upper-right corner, or pressing ``ESC`` on
their keyboard. You can configure whether this triggers a rerun of the app
by setting the ``on_dismiss`` parameter.
If a dialog is not dismissible, it must be closed programmatically by
calling ``st.rerun()`` inside the dialog function. This is useful when you
want to ensure that the dialog is always closed programmatically, such as
when the dialog contains a form that must be submitted before closing.
``st.dialog`` inherits behavior from |st.fragment|_.
When a user interacts with an input widget created inside a dialog function,
Streamlit only reruns the dialog function instead of the full script.
Calling ``st.sidebar`` in a dialog function is not supported.
Dialog code can interact with Session State, imported modules, and other
Streamlit elements created outside the dialog. Note that these interactions
are additive across multiple dialog reruns. You are responsible for
handling any side effects of that behavior.
.. warning::
Only one dialog function may be called in a script run, which means
that only one dialog can be open at any given time.
.. |st.fragment| replace:: ``st.fragment``
.. _st.fragment: https://docs.streamlit.io/develop/api-reference/execution-flow/st.fragment
Parameters
----------
title : str
The title to display at the top of the modal dialog. It cannot be empty.
The title can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
width : "small", "medium", "large"
The width of the modal dialog. This can be one of the following:
- ``"small"`` (default): The modal dialog will be a maximum of 500
pixels wide.
- ``"medium"``: The modal dialog will be up to 750 pixels wide.
- ``"large"``: The modal dialog will be up to 1280 pixels wide.
dismissible : bool
Whether the modal dialog can be dismissed by the user. If this is
``True`` (default), the user can dismiss the dialog by clicking
outside of it, clicking the "**X**" in its upper-right corner, or
pressing ``ESC`` on their keyboard. If this is ``False``, the "**X**"
in the upper-right corner is hidden and the dialog must be closed
programmatically by calling ``st.rerun()`` inside the dialog function.
.. note::
Setting ``dismissible`` to ``False`` does not guarantee that all
interactions in the main app are blocked. Don't rely on
``dismissible`` for security-critical checks.
on_dismiss : "ignore", "rerun", or callable
How the dialog should respond to dismissal events.
This can be one of the following:
- ``"ignore"`` (default): Streamlit will not rerun the app when the
user dismisses the dialog.
- ``"rerun"``: Streamlit will rerun the app when the user dismisses
the dialog.
- A ``callable``: Streamlit will rerun the app when the user dismisses
the dialog and execute the ``callable`` as a callback function
before the rest of the app.
Examples
--------
The following example demonstrates the basic usage of ``@st.dialog``.
In this app, clicking "**A**" or "**B**" will open a modal dialog and prompt you
to enter a reason for your vote. In the modal dialog, click "**Submit**" to record
your vote into Session State and rerun the app. This will close the modal dialog
since the dialog function is not called during the full-script rerun.
>>> import streamlit as st
>>>
>>> @st.dialog("Cast your vote")
>>> def vote(item):
>>> st.write(f"Why is {item} your favorite?")
>>> reason = st.text_input("Because...")
>>> if st.button("Submit"):
>>> st.session_state.vote = {"item": item, "reason": reason}
>>> st.rerun()
>>>
>>> if "vote" not in st.session_state:
>>> st.write("Vote for your favorite")
>>> if st.button("A"):
>>> vote("A")
>>> if st.button("B"):
>>> vote("B")
>>> else:
>>> f"You voted for {st.session_state.vote['item']} because {st.session_state.vote['reason']}"
.. output::
https://doc-modal-dialog.streamlit.app/
height: 350px
"""
func_or_title = title
if isinstance(func_or_title, str):
# Support passing the params via function decorator
def wrapper(f: F) -> F:
return _dialog_decorator(
non_optional_func=f,
title=func_or_title,
width=width,
dismissible=dismissible,
on_dismiss=on_dismiss,
)
return wrapper
func: F = func_or_title
return _dialog_decorator(
func, "", width=width, dismissible=dismissible, on_dismiss=on_dismiss
)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/empty.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from typing import TYPE_CHECKING, cast
from streamlit.proto.Empty_pb2 import Empty as EmptyProto
from streamlit.proto.Skeleton_pb2 import Skeleton as SkeletonProto
from streamlit.runtime.metrics_util import gather_metrics
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
class EmptyMixin:
@gather_metrics("empty")
def empty(self) -> DeltaGenerator:
"""Insert a single-element container.
Inserts a container into your app that can be used to hold a single element.
This allows you to, for example, remove elements at any point, or replace
several elements at once (using a child multi-element container).
To insert/replace/clear an element on the returned container, you can
use ``with`` notation or just call methods directly on the returned object.
See examples below.
Examples
--------
Inside a ``with st.empty():`` block, each displayed element will
replace the previous one.
>>> import streamlit as st
>>> import time
>>>
>>> with st.empty():
... for seconds in range(10):
... st.write(f"⏳ {seconds} seconds have passed")
... time.sleep(1)
... st.write(":material/check: 10 seconds over!")
... st.button("Rerun")
.. output::
https://doc-empty.streamlit.app/
height: 220px
You can use an ``st.empty`` to replace multiple elements in
succession. Use ``st.container`` inside ``st.empty`` to display (and
later replace) a group of elements.
>>> import streamlit as st
>>> import time
>>>
>>> st.button("Start over")
>>>
>>> placeholder = st.empty()
>>> placeholder.markdown("Hello")
>>> time.sleep(1)
>>>
>>> placeholder.progress(0, "Wait for it...")
>>> time.sleep(1)
>>> placeholder.progress(50, "Wait for it...")
>>> time.sleep(1)
>>> placeholder.progress(100, "Wait for it...")
>>> time.sleep(1)
>>>
>>> with placeholder.container():
... st.line_chart({"data": [1, 5, 2, 6]})
... time.sleep(1)
... st.markdown("3...")
... time.sleep(1)
... st.markdown("2...")
... time.sleep(1)
... st.markdown("1...")
... time.sleep(1)
>>>
>>> placeholder.markdown("Poof!")
>>> time.sleep(1)
>>>
>>> placeholder.empty()
.. output::
https://doc-empty-placeholder.streamlit.app/
height: 600px
"""
empty_proto = EmptyProto()
return self.dg._enqueue("empty", empty_proto)
@gather_metrics("_skeleton")
def _skeleton(self, *, height: int | None = None) -> DeltaGenerator:
"""Insert a single-element container which displays a "skeleton" placeholder.
Inserts a container into your app that can be used to hold a single element.
This allows you to, for example, remove elements at any point, or replace
several elements at once (using a child multi-element container).
To insert/replace/clear an element on the returned container, you can
use ``with`` notation or just call methods directly on the returned object.
See some of the examples below.
This is an internal method and should not be used directly.
Parameters
----------
height: int or None
Desired height of the skeleton expressed in pixels. If None, a
default height is used.
"""
skeleton_proto = SkeletonProto()
if height:
skeleton_proto.height = height
return self.dg._enqueue("skeleton", skeleton_proto)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/pdf.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import io
from pathlib import Path
from typing import TYPE_CHECKING, Any, TypeAlias, cast
from streamlit import url_util
from streamlit.elements.lib.layout_utils import validate_height
from streamlit.errors import StreamlitAPIException
from streamlit.runtime.metrics_util import gather_metrics
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
from streamlit.elements.lib.layout_utils import HeightWithoutContent
PdfData: TypeAlias = str | Path | bytes | io.BytesIO
def _get_pdf_component() -> Any | None:
"""Get the PDF custom component if available.
Returns
-------
Any | None
The pdf_viewer function if the streamlit-pdf component is available,
None otherwise.
"""
try:
import streamlit_pdf # type: ignore
return streamlit_pdf.pdf_viewer
except ImportError:
return None
class PdfMixin:
@gather_metrics("pdf")
def pdf(
self,
data: PdfData,
*,
height: HeightWithoutContent = 500,
key: str | None = None,
) -> DeltaGenerator:
"""Display a PDF viewer.
.. Important::
You must install |streamlit-pdf|_ to use this command. You can
install it as an extra with Streamlit:
.. code-block:: shell
pip install streamlit[pdf]
.. |streamlit-pdf| replace:: ``streamlit-pdf``
.. _streamlit-pdf: https://github.com/streamlit/streamlit-pdf
Parameters
----------
data : str, Path, BytesIO, or bytes
The PDF file to show. This can be one of the following:
- A URL (string) for a hosted PDF file.
- A path to a local PDF file. If you use a relative path, it must
be relative to the current working directory.
- A file-like object. For example, this can be an ``UploadedFile``
from ``st.file_uploader``, or this can be a local file opened
with ``open()``.
- Raw bytes data.
height : int or "stretch"
The height of the PDF viewer. This can be one of the following:
- An integer specifying the height in pixels: The viewer has a
fixed height. If the content is larger than the specified
height, scrolling is enabled. This is ``500`` by default.
- ``"stretch"``: The height of the viewer matches the height of
its content or the height of the parent container, whichever is
larger. If the viewer is not in a parent container, the height
of the viewer matches the height of its content.
Example
-------
>>> st.pdf("https://example.com/sample.pdf")
>>> st.pdf("https://example.com/sample.pdf", height=600)
"""
# Validate data parameter early
if data is None:
raise StreamlitAPIException(
"The PDF data cannot be None. Please provide a valid PDF file path, URL, "
"bytes data, or file-like object."
)
# Check if custom PDF component is available first
pdf_component = _get_pdf_component()
if pdf_component is None:
return self._show_pdf_warning()
return self._call_pdf_component(pdf_component, data, height, key)
def _call_pdf_component(
self,
pdf_component: Any,
data: PdfData,
height: HeightWithoutContent,
key: str | None,
) -> DeltaGenerator:
"""Call the custom PDF component with the provided data."""
# Validate height parameter after confirming component is available
validate_height(height, allow_content=False)
# Convert data to the format expected by pdf_viewer component
file_param: str | bytes
if isinstance(data, (str, Path)):
data_str = str(data).strip() # Strip whitespace from URLs
if url_util.is_url(data_str, allowed_schemas=("http", "https")):
# It's a URL - pass directly
file_param = data_str
else:
# It's a local file path - read the content as bytes for security
try:
with open(data_str, "rb") as file:
file_param = file.read()
except (FileNotFoundError, PermissionError) as e:
raise StreamlitAPIException(
f"Unable to read file '{data_str}': {e}"
)
elif isinstance(data, bytes):
# Pass bytes directly - the component will handle uploading to media storage
file_param = data
elif hasattr(data, "read") and hasattr(data, "getvalue"):
# Handle BytesIO and similar
file_param = data.getvalue()
elif hasattr(data, "read"):
# Handle other file-like objects
file_param = data.read()
else:
# Provide a more helpful error message
raise StreamlitAPIException(
f"Unsupported data type for PDF: {type(data).__name__}. "
f"Please provide a file path (str or Path), URL (str), bytes data, "
f"or file-like object (such as BytesIO or UploadedFile)."
)
# Convert to component-compatible format
if height == "stretch":
# For stretch, we need to pass a special value the component understands
# This maintains compatibility with the component while using standard layout
component_height = "stretch"
else:
component_height = str(height)
result = pdf_component(
file=file_param,
height=component_height,
key=key,
)
return cast("DeltaGenerator", result)
def _show_pdf_warning(self) -> DeltaGenerator:
"""Raise an exception that the PDF component is not available."""
raise StreamlitAPIException(
"The PDF viewer requires the `streamlit-pdf` component to be installed.\n\n"
"Please run `pip install streamlit[pdf]` to install it.\n\n"
"For more information, see the Streamlit PDF documentation at "
"https://docs.streamlit.io/develop/api-reference/media/st.pdf."
# TODO: Update this URL when docs are updated
)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/form.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import textwrap
from typing import TYPE_CHECKING, Literal, cast
from streamlit.elements.lib.form_utils import FormData, current_form_id, is_in_form
from streamlit.elements.lib.layout_utils import (
Height,
Width,
get_height_config,
get_width_config,
validate_height,
validate_width,
)
from streamlit.elements.lib.policies import (
check_cache_replay_rules,
check_session_state_rules,
)
from streamlit.elements.lib.utils import Key, to_key
from streamlit.errors import StreamlitAPIException
from streamlit.proto import Block_pb2
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner import ScriptRunContext, get_script_run_ctx
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
from streamlit.runtime.state import WidgetArgs, WidgetCallback, WidgetKwargs
def _build_duplicate_form_message(user_key: str | None = None) -> str:
if user_key is not None:
message = textwrap.dedent(
f"""
There are multiple identical forms with `key='{user_key}'`.
To fix this, please make sure that the `key` argument is unique for
each `st.form` you create.
"""
)
else:
message = textwrap.dedent(
"""
There are multiple identical forms with the same generated key.
When a form is created, it's assigned an internal key based on
its structure. Multiple forms with an identical structure will
result in the same internal key, which causes this error.
To fix this error, please pass a unique `key` argument to
`st.form`.
"""
)
return message.strip("\n")
class FormMixin:
@gather_metrics("form")
def form(
self,
key: str,
clear_on_submit: bool = False,
*,
enter_to_submit: bool = True,
border: bool = True,
width: Width = "stretch",
height: Height = "content",
) -> DeltaGenerator:
"""Create a form that batches elements together with a "Submit" button.
A form is a container that visually groups other elements and
widgets together, and contains a Submit button. When the form's
Submit button is pressed, all widget values inside the form will be
sent to Streamlit in a batch.
To add elements to a form object, you can use ``with`` notation
(preferred) or just call methods directly on the form. See
examples below.
Forms have a few constraints:
- Every form must contain a ``st.form_submit_button``.
- ``st.button`` and ``st.download_button`` cannot be added to a form.
- Forms can appear anywhere in your app (sidebar, columns, etc),
but they cannot be embedded inside other forms.
- Within a form, the only widget that can have a callback function is
``st.form_submit_button``.
Parameters
----------
key : str
A string that identifies the form. Each form must have its own
key. (This key is not displayed to the user in the interface.)
clear_on_submit : bool
If True, all widgets inside the form will be reset to their default
values after the user presses the Submit button. Defaults to False.
(Note that Custom Components are unaffected by this flag, and
will not be reset to their defaults on form submission.)
enter_to_submit : bool
Whether to submit the form when a user presses Enter while
interacting with a widget inside the form.
If this is ``True`` (default), pressing Enter while interacting
with a form widget is equivalent to clicking the first
``st.form_submit_button`` in the form.
If this is ``False``, the user must click an
``st.form_submit_button`` to submit the form.
If the first ``st.form_submit_button`` in the form is disabled,
the form will override submission behavior with
``enter_to_submit=False``.
border : bool
Whether to show a border around the form. Defaults to True.
.. note::
Not showing a border can be confusing to viewers since interacting with a
widget in the form will do nothing. You should only remove the border if
there's another border (e.g. because of an expander) or the form is small
(e.g. just a text input and a submit button).
width : "stretch", "content", or int
The width of the form container. This can be one of the following:
- ``"stretch"`` (default): The width of the container matches the
width of the parent container.
- ``"content"``: The width of the container matches the width of its
content, but doesn't exceed the width of the parent container.
- An integer specifying the width in pixels: The container has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the container matches the width
of the parent container.
height : "content", "stretch", or int
The height of the form container. This can be one of the following:
- ``"content"`` (default): The height of the container matches the
height of its content.
- ``"stretch"``: The height of the container matches the height of
its content or the height of the parent container, whichever is
larger. If the container is not in a parent container, the height
of the container matches the height of its content.
- An integer specifying the height in pixels: The container has a
fixed height. If the content is larger than the specified
height, scrolling is enabled.
.. note::
Use scrolling containers sparingly. If you use scrolling
containers, avoid heights that exceed 500 pixels. Otherwise,
the scroll surface of the container might cover the majority of
the screen on mobile devices, which makes it hard to scroll the
rest of the app.
Examples
--------
Inserting elements using ``with`` notation:
>>> import streamlit as st
>>>
>>> with st.form("my_form"):
... st.write("Inside the form")
... slider_val = st.slider("Form slider")
... checkbox_val = st.checkbox("Form checkbox")
...
... # Every form must have a submit button.
... submitted = st.form_submit_button("Submit")
... if submitted:
... st.write("slider", slider_val, "checkbox", checkbox_val)
>>> st.write("Outside the form")
.. output::
https://doc-form1.streamlit.app/
height: 425px
Inserting elements out of order:
>>> import streamlit as st
>>>
>>> form = st.form("my_form")
>>> form.slider("Inside the form")
>>> st.slider("Outside the form")
>>>
>>> # Now add a submit button to the form:
>>> form.form_submit_button("Submit")
.. output::
https://doc-form2.streamlit.app/
height: 375px
"""
if is_in_form(self.dg):
raise StreamlitAPIException("Forms cannot be nested in other forms.")
check_cache_replay_rules()
check_session_state_rules(default_value=None, key=key, writes_allowed=False)
# A form is uniquely identified by its key.
form_id = key
ctx = get_script_run_ctx()
if ctx is not None:
new_form_id = form_id not in ctx.form_ids_this_run
if new_form_id:
ctx.form_ids_this_run.add(form_id)
else:
raise StreamlitAPIException(_build_duplicate_form_message(key))
block_proto = Block_pb2.Block()
block_proto.form.form_id = form_id
block_proto.form.clear_on_submit = clear_on_submit
block_proto.form.enter_to_submit = enter_to_submit
block_proto.form.border = border
validate_width(width, allow_content=True)
block_proto.width_config.CopyFrom(get_width_config(width))
validate_height(height, allow_content=True)
block_proto.height_config.CopyFrom(get_height_config(height))
block_dg = self.dg._block(block_proto)
# Attach the form's button info to the newly-created block's
# DeltaGenerator.
block_dg._form_data = FormData(form_id)
return block_dg
@gather_metrics("form_submit_button")
def form_submit_button(
self,
label: str = "Submit",
help: str | None = None,
on_click: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
key: Key | None = None,
type: Literal["primary", "secondary", "tertiary"] = "secondary",
icon: str | None = None,
disabled: bool = False,
use_container_width: bool | None = None,
width: Width = "content",
shortcut: str | None = None,
) -> bool:
r"""Display a form submit button.
When this button is clicked, all widget values inside the form will be
sent from the user's browser to your Streamlit server in a batch.
Every form must have at least one ``st.form_submit_button``. An
``st.form_submit_button`` cannot exist outside of a form.
For more information about forms, check out our `docs
<https://docs.streamlit.io/develop/concepts/architecture/forms>`_.
Parameters
----------
label : str
A short label explaining to the user what this button is for. This
defaults to ``"Submit"``. The label can optionally contain
GitHub-flavored Markdown of the following types: Bold, Italics,
Strikethroughs, Inline Code, Links, and Images. Images display like
icons, with a max height equal to the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
help : str or None
A tooltip that gets displayed when the button is hovered over. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
on_click : callable
An optional callback invoked when this button is clicked.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. No two widgets may have the same key.
type : "primary", "secondary", or "tertiary"
An optional string that specifies the button type. This can be one
of the following:
- ``"primary"``: The button's background is the app's primary color
for additional emphasis.
- ``"secondary"`` (default): The button's background coordinates
with the app's background color for normal emphasis.
- ``"tertiary"``: The button is plain text without a border or
background for subtlety.
icon : str or None
An optional emoji or icon to display next to the button label. If ``icon``
is ``None`` (default), no icon is displayed. If ``icon`` is a
string, the following options are valid:
- A single-character emoji. For example, you can set ``icon="🚨"``
or ``icon="🔥"``. Emoji short codes are not supported.
- An icon from the Material Symbols library (rounded style) in the
format ``":material/icon_name:"`` where "icon_name" is the name
of the icon in snake case.
For example, ``icon=":material/thumb_up:"`` will display the
Thumb Up icon. Find additional icons in the `Material Symbols
<https://fonts.google.com/icons?icon.set=Material+Symbols&icon.style=Rounded>`_
font library.
- ``"spinner"``: Displays a spinner as an icon.
disabled : bool
Whether to disable the button. If this is ``False`` (default), the
user can interact with the button. If this is ``True``, the button
is grayed-out and can't be clicked.
If the first ``st.form_submit_button`` in the form is disabled,
the form will override submission behavior with
``enter_to_submit=False``.
use_container_width : bool
Whether to expand the button's width to fill its parent container.
If ``use_container_width`` is ``False`` (default), Streamlit sizes
the button to fit its contents. If ``use_container_width`` is
``True``, the width of the button matches its parent container.
In both cases, if the contents of the button are wider than the
parent container, the contents will line wrap.
.. deprecated::
``use_container_width`` is deprecated and will be removed in a
future release. For ``use_container_width=True``, use
``width="stretch"``. For ``use_container_width=False``, use
``width="content"``.
width : "content", "stretch", or int
The width of the button. This can be one of the following:
- ``"content"`` (default): The width of the button matches the
width of its content, but doesn't exceed the width of the parent
container.
- ``"stretch"``: The width of the button matches the width of the
parent container.
- An integer specifying the width in pixels: The button has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the button matches the width
of the parent container.
shortcut : str or None
An optional keyboard shortcut that triggers the button. This can be
one of the following strings:
- A single alphanumeric key like ``"K"`` or ``"4"``.
- A function key like ``"F11"``.
- A special key like ``"Enter"``, ``"Esc"``, or ``"Tab"``.
- Any of the above combined with modifiers. For example, you can use
``"Ctrl+K"`` or ``"Cmd+Shift+O"``.
.. important::
The keys ``"C"`` and ``"R"`` are reserved and can't be used,
even with modifiers. Punctuation keys like ``"."`` and ``","``
aren't currently supported.
For a list of supported keys and modifiers, see the documentation
for |st.button|_.
.. |st.button| replace:: ``st.button``
.. _st.button: https://docs.streamlit.io/develop/api-reference/widgets/st.button
Returns
-------
bool
True if the button was clicked.
"""
ctx = get_script_run_ctx()
if use_container_width is not None:
width = "stretch" if use_container_width else "content"
# Checks whether the entered button type is one of the allowed options
if type not in ["primary", "secondary", "tertiary"]:
raise StreamlitAPIException(
'The type argument to st.form_submit_button must be "primary", "secondary", or "tertiary". \n'
f'The argument passed was "{type}".'
)
return self._form_submit_button(
label=label,
help=help,
on_click=on_click,
args=args,
kwargs=kwargs,
type=type,
icon=icon,
disabled=disabled,
ctx=ctx,
width=width,
key=key,
shortcut=shortcut,
)
def _form_submit_button(
self,
label: str = "Submit",
help: str | None = None,
on_click: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
key: Key | None = None,
type: Literal["primary", "secondary", "tertiary"] = "secondary",
icon: str | None = None,
disabled: bool = False,
ctx: ScriptRunContext | None = None,
width: Width = "content",
shortcut: str | None = None,
) -> bool:
form_id = current_form_id(self.dg)
submit_button_key = to_key(key) or f"FormSubmitter:{form_id}-{label}"
return self.dg._button(
label=label,
key=submit_button_key,
help=help,
is_form_submitter=True,
on_click=on_click,
args=args,
kwargs=kwargs,
type=type,
icon=icon,
disabled=disabled,
ctx=ctx,
width=width,
shortcut=shortcut,
)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/toast.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from typing import TYPE_CHECKING, Literal, cast
from streamlit.errors import StreamlitAPIException, StreamlitValueError
from streamlit.proto.Toast_pb2 import Toast as ToastProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.string_util import clean_text, validate_icon_or_emoji
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
from streamlit.type_util import SupportsStr
def validate_text(toast_text: SupportsStr) -> SupportsStr:
if str(toast_text) == "":
raise StreamlitAPIException(
"Toast body cannot be blank - please provide a message."
)
return toast_text
class ToastMixin:
@gather_metrics("toast")
def toast(
self,
body: SupportsStr,
*, # keyword-only args:
icon: str | None = None,
duration: Literal["short", "long", "infinite"] | int = "short",
) -> DeltaGenerator:
"""Display a short message, known as a notification "toast".
The toast appears in the app's top-right corner and disappears after four seconds.
.. warning::
``st.toast`` is not compatible with Streamlit's `caching \
<https://docs.streamlit.io/develop/concepts/architecture/caching>`_ and
cannot be called within a cached function.
Parameters
----------
body : str
The string to display as GitHub-flavored Markdown. Syntax
information can be found at: https://github.github.com/gfm.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
icon : str, None
An optional emoji or icon to display next to the alert. If ``icon``
is ``None`` (default), no icon is displayed. If ``icon`` is a
string, the following options are valid:
- A single-character emoji. For example, you can set ``icon="🚨"``
or ``icon="🔥"``. Emoji short codes are not supported.
- An icon from the Material Symbols library (rounded style) in the
format ``":material/icon_name:"`` where "icon_name" is the name
of the icon in snake case.
For example, ``icon=":material/thumb_up:"`` will display the
Thumb Up icon. Find additional icons in the `Material Symbols \
<https://fonts.google.com/icons?icon.set=Material+Symbols&icon.style=Rounded>`_
font library.
- ``"spinner"``: Displays a spinner as an icon.
duration : "short", "long", "infinite", or int
The time to display the toast message. This can be one of the
following:
- ``"short"`` (default): Displays for 4 seconds.
- ``"long"``: Displays for 10 seconds.
- ``"infinite"``: Shows the toast until the user dismisses it.
- An integer: Displays for the specified number of seconds.
Examples
--------
**Example 1: Show a toast message**
>>> import streamlit as st
>>>
>>> st.toast("Your edited image was saved!", icon="😍")
.. output::
https://doc-status-toast.streamlit.app
height: 200px
**Example 2: Show multiple toasts**
When multiple toasts are generated, they will stack. Hovering over a
toast will stop it from disappearing. When hovering ends, the toast
will disappear after time specified in ``duration``.
>>> import time
>>> import streamlit as st
>>>
>>> if st.button("Three cheers"):
>>> st.toast("Hip!")
>>> time.sleep(0.5)
>>> st.toast("Hip!")
>>> time.sleep(0.5)
>>> st.toast("Hooray!", icon="🎉")
.. output::
https://doc-status-toast1.streamlit.app
height: 300px
**Example 3: Update a toast message**
Toast messages can also be updated. Assign ``st.toast(my_message)`` to
a variable and use the ``.toast()`` method to update it. If a toast has
already disappeared or been dismissed, the update will not be seen.
>>> import time
>>> import streamlit as st
>>>
>>> def cook_breakfast():
>>> msg = st.toast("Gathering ingredients...")
>>> time.sleep(1)
>>> msg.toast("Cooking...")
>>> time.sleep(1)
>>> msg.toast("Ready!", icon="🥞")
>>>
>>> if st.button("Cook breakfast"):
>>> cook_breakfast()
.. output::
https://doc-status-toast2.streamlit.app
height: 200px
"""
toast_proto = ToastProto()
toast_proto.body = clean_text(validate_text(body))
toast_proto.icon = validate_icon_or_emoji(icon)
if duration in ["short", "long", "infinite"] or (
isinstance(duration, int) and duration > 0
):
if duration == "short":
toast_proto.duration = 4
elif duration == "long":
toast_proto.duration = 10
elif duration == "infinite":
toast_proto.duration = 0
else:
toast_proto.duration = duration
else:
raise StreamlitValueError(
"duration", ["short", "long", "infinite", "a positive integer"]
)
return self.dg._enqueue("toast", toast_proto)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/elements/arrow.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import json
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
Any,
Final,
Literal,
TypeAlias,
TypedDict,
cast,
overload,
)
from streamlit import dataframe_util
from streamlit.deprecation_util import (
make_deprecated_name_warning,
show_deprecation_warning,
)
from streamlit.elements.lib.column_config_utils import (
INDEX_IDENTIFIER,
ColumnConfigMappingInput,
apply_data_specific_configs,
marshall_column_config,
process_config_mapping,
update_column_config,
)
from streamlit.elements.lib.form_utils import current_form_id
from streamlit.elements.lib.layout_utils import (
Height,
LayoutConfig,
Width,
validate_height,
validate_width,
)
from streamlit.elements.lib.pandas_styler_utils import marshall_styler
from streamlit.elements.lib.policies import check_widget_policies
from streamlit.elements.lib.utils import Key, compute_and_register_element_id, to_key
from streamlit.errors import StreamlitAPIException, StreamlitValueError
from streamlit.proto.Arrow_pb2 import Arrow as ArrowProto
from streamlit.proto.ForwardMsg_pb2 import ForwardMsg
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner_utils.script_run_context import (
enqueue_message,
get_script_run_ctx,
)
from streamlit.runtime.state import WidgetCallback, register_widget
from streamlit.util import AttributeDictionary
if TYPE_CHECKING:
from collections.abc import Hashable, Iterable
from numpy import typing as npt
from pandas import DataFrame
from streamlit.dataframe_util import Data
from streamlit.delta_generator import DeltaGenerator
from streamlit.elements.lib.built_in_chart_utils import AddRowsMetadata
SelectionMode: TypeAlias = Literal[
"single-row",
"multi-row",
"single-column",
"multi-column",
"single-cell",
"multi-cell",
]
_SELECTION_MODES: Final[set[SelectionMode]] = {
"single-row",
"multi-row",
"single-column",
"multi-column",
"single-cell",
"multi-cell",
}
class DataframeSelectionState(TypedDict, total=False):
"""
The schema for the dataframe selection state.
The selection state is stored in a dictionary-like object that supports both
key and attribute notation. Selection states cannot be programmatically
changed or set through Session State.
.. warning::
If a user sorts a dataframe, row selections will be reset. If your
users need to sort and filter the dataframe to make selections, direct
them to use the search function in the dataframe toolbar instead.
Attributes
----------
rows : list[int]
The selected rows, identified by their integer position. The integer
positions match the original dataframe, even if the user sorts the
dataframe in their browser. For a ``pandas.DataFrame``, you can
retrieve data from its integer position using methods like ``.iloc[]``
or ``.iat[]``.
columns : list[str]
The selected columns, identified by their names.
cells : list[tuple[int, str]]
The selected cells, provided as a tuple of row integer position
and column name. For example, the first cell in a column named "col 1"
is represented as ``(0, "col 1")``. Cells within index columns are not
returned.
Example
-------
The following example has multi-row and multi-column selections enabled.
Try selecting some rows. To select multiple columns, hold ``CMD`` (macOS)
or ``Ctrl`` (Windows) while selecting columns. Hold ``Shift`` to select a
range of columns.
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(
... rng(0).standard_normal((12, 5)), columns=["a", "b", "c", "d", "e"]
... )
>>>
>>> event = st.dataframe(
... df,
... key="data",
... on_select="rerun",
... selection_mode=["multi-row", "multi-column", "multi-cell"],
... )
>>>
>>> event.selection
.. output::
https://doc-dataframe-events-selection-state.streamlit.app
height: 600px
"""
rows: list[int]
columns: list[str]
cells: list[tuple[int, str]]
class DataframeState(TypedDict, total=False):
"""
The schema for the dataframe event state.
The event state is stored in a dictionary-like object that supports both
key and attribute notation. Event states cannot be programmatically
changed or set through Session State.
Only selection events are supported at this time.
Attributes
----------
selection : dict
The state of the ``on_select`` event. This attribute returns a
dictionary-like object that supports both key and attribute notation.
The attributes are described by the ``DataframeSelectionState``
dictionary schema.
"""
selection: DataframeSelectionState
@dataclass
class DataframeSelectionSerde:
"""DataframeSelectionSerde is used to serialize and deserialize the dataframe selection state."""
def deserialize(self, ui_value: str | None) -> DataframeState:
empty_selection_state: DataframeState = {
"selection": {
"rows": [],
"columns": [],
"cells": [],
},
}
selection_state: DataframeState = (
empty_selection_state if ui_value is None else json.loads(ui_value)
)
if "selection" not in selection_state:
selection_state = empty_selection_state
if "rows" not in selection_state["selection"]:
selection_state["selection"]["rows"] = []
if "columns" not in selection_state["selection"]:
selection_state["selection"]["columns"] = []
if "cells" not in selection_state["selection"]:
selection_state["selection"]["cells"] = []
else:
# Explicitly convert all cells to a tuple (from list).
# This is necessary since there isn't a concept of tuples in JSON
# The format that the data is transferred to the backend.
selection_state["selection"]["cells"] = [
tuple(cell) # type: ignore
for cell in selection_state["selection"]["cells"]
]
return cast("DataframeState", AttributeDictionary(selection_state))
def serialize(self, state: DataframeState) -> str:
return json.dumps(state)
def parse_selection_mode(
selection_mode: SelectionMode | Iterable[SelectionMode],
) -> set[ArrowProto.SelectionMode.ValueType]:
"""Parse and check the user provided selection modes."""
if isinstance(selection_mode, str):
# Only a single selection mode was passed
selection_mode_set = {selection_mode}
else:
# Multiple selection modes were passed
selection_mode_set = set(selection_mode)
if not selection_mode_set.issubset(_SELECTION_MODES):
raise StreamlitAPIException(
f"Invalid selection mode: {selection_mode}. "
f"Valid options are: {_SELECTION_MODES}"
)
if selection_mode_set.issuperset({"single-row", "multi-row"}):
raise StreamlitAPIException(
"Only one of `single-row` or `multi-row` can be selected as selection mode."
)
if selection_mode_set.issuperset({"single-column", "multi-column"}):
raise StreamlitAPIException(
"Only one of `single-column` or `multi-column` can be selected as selection mode."
)
if selection_mode_set.issuperset({"single-cell", "multi-cell"}):
raise StreamlitAPIException(
"Only one of `single-cell` or `multi-cell` can be selected as selection mode."
)
parsed_selection_modes = []
for mode in selection_mode_set:
if mode == "single-row":
parsed_selection_modes.append(ArrowProto.SelectionMode.SINGLE_ROW)
elif mode == "multi-row":
parsed_selection_modes.append(ArrowProto.SelectionMode.MULTI_ROW)
elif mode == "single-column":
parsed_selection_modes.append(ArrowProto.SelectionMode.SINGLE_COLUMN)
elif mode == "multi-column":
parsed_selection_modes.append(ArrowProto.SelectionMode.MULTI_COLUMN)
elif mode == "single-cell":
parsed_selection_modes.append(ArrowProto.SelectionMode.SINGLE_CELL)
elif mode == "multi-cell":
parsed_selection_modes.append(ArrowProto.SelectionMode.MULTI_CELL)
return set(parsed_selection_modes)
def parse_border_mode(
border: bool | Literal["horizontal"],
) -> ArrowProto.BorderMode.ValueType:
"""Parse and check the user provided border mode."""
if isinstance(border, bool):
return ArrowProto.BorderMode.ALL if border else ArrowProto.BorderMode.NONE
if border == "horizontal":
return ArrowProto.BorderMode.HORIZONTAL
raise StreamlitValueError("border", ["True", "False", "'horizontal'"])
class ArrowMixin:
@overload
def dataframe(
self,
data: Data = None,
width: Width = "stretch",
height: Height | Literal["auto"] = "auto",
*,
use_container_width: bool | None = None,
hide_index: bool | None = None,
column_order: Iterable[str] | None = None,
column_config: ColumnConfigMappingInput | None = None,
key: Key | None = None,
on_select: Literal["ignore"] = "ignore",
selection_mode: SelectionMode | Iterable[SelectionMode] = "multi-row",
row_height: int | None = None,
placeholder: str | None = None,
) -> DeltaGenerator: ...
@overload
def dataframe(
self,
data: Data = None,
width: Width = "stretch",
height: Height | Literal["auto"] = "auto",
*,
use_container_width: bool | None = None,
hide_index: bool | None = None,
column_order: Iterable[str] | None = None,
column_config: ColumnConfigMappingInput | None = None,
key: Key | None = None,
on_select: Literal["rerun"] | WidgetCallback,
selection_mode: SelectionMode | Iterable[SelectionMode] = "multi-row",
row_height: int | None = None,
placeholder: str | None = None,
) -> DataframeState: ...
@gather_metrics("dataframe")
def dataframe(
self,
data: Data = None,
width: Width = "stretch",
height: Height | Literal["auto"] = "auto",
*,
use_container_width: bool | None = None,
hide_index: bool | None = None,
column_order: Iterable[str] | None = None,
column_config: ColumnConfigMappingInput | None = None,
key: Key | None = None,
on_select: Literal["ignore", "rerun"] | WidgetCallback = "ignore",
selection_mode: SelectionMode | Iterable[SelectionMode] = "multi-row",
row_height: int | None = None,
placeholder: str | None = None,
) -> DeltaGenerator | DataframeState:
"""Display a dataframe as an interactive table.
This command works with a wide variety of collection-like and
dataframe-like object types.
Parameters
----------
data : dataframe-like, collection-like, or None
The data to display.
Dataframe-like objects include dataframe and series objects from
popular libraries like Dask, Modin, Numpy, pandas, Polars, PyArrow,
Snowpark, Xarray, and more. You can use database cursors and
clients that comply with the
`Python Database API Specification v2.0 (PEP 249)
<https://peps.python.org/pep-0249/>`_. Additionally, you can use
anything that supports the `Python dataframe interchange protocol
<https://data-apis.org/dataframe-protocol/latest/>`_.
For example, you can use the following:
- ``pandas.DataFrame``, ``pandas.Series``, ``pandas.Index``,
``pandas.Styler``, and ``pandas.Array``
- ``polars.DataFrame``, ``polars.LazyFrame``, and ``polars.Series``
- ``snowflake.snowpark.dataframe.DataFrame``,
``snowflake.snowpark.table.Table``
If a data type is not recognized, Streamlit will convert the object
to a ``pandas.DataFrame`` or ``pyarrow.Table`` using a
``.to_pandas()`` or ``.to_arrow()`` method, respectively, if
available.
If ``data`` is a ``pandas.Styler``, it will be used to style its
underlying ``pandas.DataFrame``. Streamlit supports custom cell
values, colors, and font weights. It does not support some of the
more exotic styling options, like bar charts, hovering, and
captions. For these styling options, use column configuration
instead. Text and number formatting from ``column_config`` always
takes precedence over text and number formatting from ``pandas.Styler``.
Collection-like objects include all Python-native ``Collection``
types, such as ``dict``, ``list``, and ``set``.
If ``data`` is ``None``, Streamlit renders an empty table.
width : "stretch", "content", or int
The width of the dataframe element. This can be one of the following:
- ``"stretch"`` (default): The width of the element matches the
width of the parent container.
- ``"content"``: The width of the element matches the width of its
content, but doesn't exceed the width of the parent container.
- An integer specifying the width in pixels: The element has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the element matches the width
of the parent container.
height : "auto", "content", "stretch", or int
The height of the dataframe element. This can be one of the following:
- ``"auto"`` (default): Streamlit sets the height to show at most
ten rows.
- ``"content"``: The height of the element matches the height of
its content. The height is capped at 10,000 pixels to prevent
performance issues with very large dataframes.
- ``"stretch"``: The height of the element expands to fill the
available vertical space in its parent container. When multiple
elements with stretch height are in the same container, they
share the available vertical space evenly. The dataframe will
maintain a minimum height to display up to three rows, but
otherwise won't exceed the available height in its parent
container.
- An integer specifying the height in pixels: The element has a
fixed height.
Vertical scrolling within the dataframe element is enabled when the
height does not accommodate all rows.
use_container_width : bool
Whether to override ``width`` with the width of the parent
container. If this is ``True`` (default), Streamlit sets the width
of the dataframe to match the width of the parent container. If
this is ``False``, Streamlit sets the dataframe's width according
to ``width``.
.. deprecated::
``use_container_width`` is deprecated and will be removed in a
future release. For ``use_container_width=True``, use
``width="stretch"``.
hide_index : bool or None
Whether to hide the index column(s). If ``hide_index`` is ``None``
(default), the visibility of index columns is automatically
determined based on the data and other configurations.
column_order : Iterable[str] or None
The ordered list of columns to display. If this is ``None``
(default), Streamlit displays all columns in the order inherited
from the underlying data structure. If this is a list, the
indicated columns will display in the order they appear within the
list. Columns may be omitted or repeated within the list.
For example, ``column_order=("col2", "col1")`` will display
``"col2"`` first, followed by ``"col1"``, and will hide all other
non-index columns.
``column_order`` does not accept positional column indices and
can't move the index column(s).
column_config : dict or None
Configuration to customize how columns are displayed. If this is
``None`` (default), columns are styled based on the underlying data
type of each column.
Column configuration can modify column names, visibility, type,
width, format, and more. If this is a dictionary, the keys are
column names (strings) and/or positional column indices (integers),
and the values are one of the following:
- ``None`` to hide the column.
- A string to set the display label of the column.
- One of the column types defined under ``st.column_config``. For
example, to show a column as dollar amounts, use
``st.column_config.NumberColumn("Dollar values", format="$ %d")``.
See more info on the available column types and config options
`here <https://docs.streamlit.io/develop/api-reference/data/st.column_config>`_.
To configure the index column(s), use ``"_index"`` as the column
name, or use a positional column index where ``0`` refers to the
first index column.
key : str
An optional string to use for giving this element a stable
identity. If ``key`` is ``None`` (default), this element's identity
will be determined based on the values of the other parameters.
Additionally, if selections are activated and ``key`` is provided,
Streamlit will register the key in Session State to store the
selection state. The selection state is read-only.
on_select : "ignore" or "rerun" or callable
How the dataframe should respond to user selection events. This
controls whether or not the dataframe behaves like an input widget.
``on_select`` can be one of the following:
- ``"ignore"`` (default): Streamlit will not react to any selection
events in the dataframe. The dataframe will not behave like an
input widget.
- ``"rerun"``: Streamlit will rerun the app when the user selects
rows, columns, or cells in the dataframe. In this case,
``st.dataframe`` will return the selection data as a dictionary.
- A ``callable``: Streamlit will rerun the app and execute the
``callable`` as a callback function before the rest of the app.
In this case, ``st.dataframe`` will return the selection data
as a dictionary.
selection_mode : "single-row", "multi-row", "single-column", \
"multi-column", "single-cell", "multi-cell", or Iterable of these
The types of selections Streamlit should allow when selections are
enabled with ``on_select``. This can be one of the following:
- "multi-row" (default): Multiple rows can be selected at a time.
- "single-row": Only one row can be selected at a time.
- "multi-column": Multiple columns can be selected at a time.
- "single-column": Only one column can be selected at a time.
- "multi-cell": A rectangular range of cells can be selected.
- "single-cell": Only one cell can be selected at a time.
- An ``Iterable`` of the above options: The table will allow
selection based on the modes specified. For example, to allow the
user to select multiple rows and multiple cells, use
``["multi-row", "multi-cell"]``.
When column selections are enabled, column sorting is disabled.
row_height : int or None
The height of each row in the dataframe in pixels. If ``row_height``
is ``None`` (default), Streamlit will use a default row height,
which fits one line of text.
placeholder : str or None
The text that should be shown for missing values. If this is
``None`` (default), missing values are displayed as "None". To
leave a cell empty, use an empty string (``""``). Other common
values are ``"null"``, ``"NaN"`` and ``"-"``.
Returns
-------
element or dict
If ``on_select`` is ``"ignore"`` (default), this command returns an
internal placeholder for the dataframe element that can be used
with the ``.add_rows()`` method. Otherwise, this command returns a
dictionary-like object that supports both key and attribute
notation. The attributes are described by the ``DataframeState``
dictionary schema.
Examples
--------
**Example 1: Display a dataframe**
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(
... rng(0).standard_normal((50, 20)), columns=("col %d" % i for i in range(20))
... )
>>>
>>> st.dataframe(df)
.. output::
https://doc-dataframe.streamlit.app/
height: 500px
**Example 2: Use Pandas Styler**
You can also pass a Pandas Styler object to change the style of
the rendered DataFrame:
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(
... rng(0).standard_normal((10, 20)), columns=("col %d" % i for i in range(20))
... )
>>>
>>> st.dataframe(df.style.highlight_max(axis=0))
.. output::
https://doc-dataframe1.streamlit.app/
height: 500px
**Example 3: Use column configuration**
You can customize a dataframe via ``column_config``, ``hide_index``, or ``column_order``.
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(
... {
... "name": ["Roadmap", "Extras", "Issues"],
... "url": [
... "https://roadmap.streamlit.app",
... "https://extras.streamlit.app",
... "https://issues.streamlit.app",
... ],
... "stars": rng(0).integers(0, 1000, size=3),
... "views_history": rng(0).integers(0, 5000, size=(3, 30)).tolist(),
... }
... )
>>>
>>> st.dataframe(
... df,
... column_config={
... "name": "App name",
... "stars": st.column_config.NumberColumn(
... "Github Stars",
... help="Number of stars on GitHub",
... format="%d ⭐",
... ),
... "url": st.column_config.LinkColumn("App URL"),
... "views_history": st.column_config.LineChartColumn(
... "Views (past 30 days)", y_min=0, y_max=5000
... ),
... },
... hide_index=True,
... )
.. output::
https://doc-dataframe-config.streamlit.app/
height: 350px
**Example 4: Customize your index**
You can use column configuration to format your index.
>>> from datetime import datetime, date
>>> import numpy as np
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> @st.cache_data
>>> def load_data():
>>> year = datetime.now().year
>>> df = pd.DataFrame(
... {
... "Date": [date(year, month, 1) for month in range(1, 4)],
... "Total": np.random.randint(1000, 5000, size=3),
... }
... )
>>> df.set_index("Date", inplace=True)
>>> return df
>>>
>>> df = load_data()
>>> config = {
... "_index": st.column_config.DateColumn("Month", format="MMM YYYY"),
... "Total": st.column_config.NumberColumn("Total ($)"),
... }
>>>
>>> st.dataframe(df, column_config=config)
.. output::
https://doc-dataframe-config-index.streamlit.app/
height: 225px
"""
import pyarrow as pa
if on_select not in ["ignore", "rerun"] and not callable(on_select):
raise StreamlitAPIException(
f"You have passed {on_select} to `on_select`. But only 'ignore', "
"'rerun', or a callable is supported."
)
key = to_key(key)
is_selection_activated = on_select != "ignore"
if is_selection_activated:
# Run some checks that are only relevant when selections are activated
is_callback = callable(on_select)
check_widget_policies(
self.dg,
key,
on_change=cast("WidgetCallback", on_select) if is_callback else None,
default_value=None,
writes_allowed=False,
enable_check_callback_rules=is_callback,
)
if use_container_width is not None:
show_deprecation_warning(
make_deprecated_name_warning(
"use_container_width",
"width",
"2025-12-31",
"For `use_container_width=True`, use `width='stretch'`. "
"For `use_container_width=False`, use `width='content'`.",
include_st_prefix=False,
),
show_in_browser=False,
)
if use_container_width:
width = "stretch"
elif not isinstance(width, int):
width = "content"
validate_width(width, allow_content=True)
validate_height(
height,
allow_content=True,
additional_allowed=["auto"],
)
# Convert the user provided column config into the frontend compatible format:
column_config_mapping = process_config_mapping(column_config)
proto = ArrowProto()
if row_height:
proto.row_height = row_height
if column_order:
proto.column_order[:] = column_order
if placeholder is not None:
proto.placeholder = placeholder
proto.editing_mode = ArrowProto.EditingMode.READ_ONLY
has_range_index: bool = False
if isinstance(data, pa.Table):
# For pyarrow tables, we can just serialize the table directly
proto.data = dataframe_util.convert_arrow_table_to_arrow_bytes(data)
else:
# For all other data formats, we need to convert them to a pandas.DataFrame
# thereby, we also apply some data specific configs
# Determine the input data format
data_format = dataframe_util.determine_data_format(data)
if dataframe_util.is_pandas_styler(data):
# If pandas.Styler uuid is not provided, a hash of the position
# of the element will be used. This will cause a rerender of the table
# when the position of the element is changed.
delta_path = self.dg._get_delta_path_str()
default_uuid = str(hash(delta_path))
marshall_styler(proto, data, default_uuid)
# Convert the input data into a pandas.DataFrame
data_df = dataframe_util.convert_anything_to_pandas_df(
data, ensure_copy=False
)
has_range_index = dataframe_util.has_range_index(data_df)
apply_data_specific_configs(column_config_mapping, data_format)
# Serialize the data to bytes:
proto.data = dataframe_util.convert_pandas_df_to_arrow_bytes(data_df)
if hide_index is not None:
update_column_config(
column_config_mapping, INDEX_IDENTIFIER, {"hidden": hide_index}
)
elif (
# Hide index column if row selections are activated and the dataframe has a range index.
# The range index usually does not add a lot of value.
is_selection_activated
and selection_mode in ["multi-row", "single-row"]
and has_range_index
):
update_column_config(
column_config_mapping, INDEX_IDENTIFIER, {"hidden": True}
)
marshall_column_config(proto, column_config_mapping)
# Create layout configuration
# For height, only include it in LayoutConfig if it's not "auto"
# "auto" is the default behavior and doesn't need to be sent
layout_config = LayoutConfig(
width=width, height=height if height != "auto" else None
)
if is_selection_activated:
# If selection events are activated, we need to register the dataframe
# element as a widget.
proto.selection_mode.extend(parse_selection_mode(selection_mode))
proto.form_id = current_form_id(self.dg)
ctx = get_script_run_ctx()
proto.id = compute_and_register_element_id(
"dataframe",
user_key=key,
key_as_main_identity=False,
dg=self.dg,
data=proto.data,
width=width,
height=height,
use_container_width=use_container_width,
column_order=proto.column_order,
column_config=proto.columns,
selection_mode=selection_mode,
is_selection_activated=is_selection_activated,
row_height=row_height,
placeholder=placeholder,
)
serde = DataframeSelectionSerde()
widget_state = register_widget(
proto.id,
on_change_handler=on_select if callable(on_select) else None,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="string_value",
)
self.dg._enqueue("arrow_data_frame", proto, layout_config=layout_config)
return widget_state.value
return self.dg._enqueue("arrow_data_frame", proto, layout_config=layout_config)
@gather_metrics("table")
def table(
self, data: Data = None, *, border: bool | Literal["horizontal"] = True
) -> DeltaGenerator:
"""Display a static table.
While ``st.dataframe`` is geared towards large datasets and interactive
data exploration, ``st.table`` is useful for displaying small, styled
tables without sorting or scrolling. For example, ``st.table`` may be
the preferred way to display a confusion matrix or leaderboard.
Additionally, ``st.table`` supports Markdown.
Parameters
----------
data : Anything supported by st.dataframe
The table data.
All cells including the index and column headers can optionally
contain GitHub-flavored Markdown. Syntax information can be found
at: https://github.github.com/gfm.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
border : bool or "horizontal"
Whether to show borders around the table and between cells. This can be one
of the following:
- ``True`` (default): Show borders around the table and between cells.
- ``False``: Don't show any borders.
- ``"horizontal"``: Show only horizontal borders between rows.
Examples
--------
**Example 1: Display a confusion matrix as a static table**
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> confusion_matrix = pd.DataFrame(
... {
... "Predicted Cat": [85, 3, 2, 1],
... "Predicted Dog": [2, 78, 4, 0],
... "Predicted Bird": [1, 5, 72, 3],
... "Predicted Fish": [0, 2, 1, 89],
... },
... index=["Actual Cat", "Actual Dog", "Actual Bird", "Actual Fish"],
... )
>>> st.table(confusion_matrix)
.. output::
https://doc-table-confusion.streamlit.app/
height: 250px
**Example 2: Display a product leaderboard with Markdown and horizontal borders**
>>> import streamlit as st
>>>
>>> product_data = {
... "Product": [
... ":material/devices: Widget Pro",
... ":material/smart_toy: Smart Device",
... ":material/inventory: Premium Kit",
... ],
... "Category": [":blue[Electronics]", ":green[IoT]", ":violet[Bundle]"],
... "Stock": ["🟢 Full", "🟡 Low", "🔴 Empty"],
... "Units sold": [1247, 892, 654],
... "Revenue": [125000, 89000, 98000],
... }
>>> st.table(product_data, border="horizontal")
.. output::
https://doc-table-horizontal-border.streamlit.app/
height: 200px
"""
# Parse border parameter to enum value
border_mode = parse_border_mode(border)
# Check if data is uncollected, and collect it but with 100 rows max, instead of
# 10k rows, which is done in all other cases.
# We use 100 rows in st.table, because large tables render slowly,
# take too much screen space, and can crush the app.
if dataframe_util.is_unevaluated_data_object(data):
data = dataframe_util.convert_anything_to_pandas_df(
data, max_unevaluated_rows=100
)
# If pandas.Styler uuid is not provided, a hash of the position
# of the element will be used. This will cause a rerender of the table
# when the position of the element is changed.
delta_path = self.dg._get_delta_path_str()
default_uuid = str(hash(delta_path))
# Tables dimensions are not configurable, this ensures that
# styles are applied correctly on the element container in the frontend.
layout_config = LayoutConfig(
width="stretch",
height="content",
)
proto = ArrowProto()
marshall(proto, data, default_uuid)
proto.border_mode = border_mode
return self.dg._enqueue("arrow_table", proto, layout_config=layout_config)
@gather_metrics("add_rows")
def add_rows(self, data: Data = None, **kwargs: Any) -> DeltaGenerator | None:
"""Concatenate a dataframe to the bottom of the current one.
.. important::
``add_rows`` is deprecated and might be removed in a future version.
If you have a specific use-case that requires the ``add_rows``
functionality, please tell us via this
[issue on Github](https://github.com/streamlit/streamlit/issues/13063).
Parameters
----------
data : pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, Iterable, dict, or None
Table to concat. Optional.
**kwargs : pandas.DataFrame, numpy.ndarray, Iterable, dict, or None
The named dataset to concat. Optional. You can only pass in 1
dataset (including the one in the data parameter).
Example
-------
>>> import time
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df1 = pd.DataFrame(
>>> rng(0).standard_normal(size=(50, 20)), columns=("col %d" % i for i in range(20))
>>> )
>>>
>>> df2 = pd.DataFrame(
>>> rng(1).standard_normal(size=(50, 20)), columns=("col %d" % i for i in range(20))
>>> )
>>>
>>> my_table = st.table(df1)
>>> time.sleep(1)
>>> my_table.add_rows(df2)
You can do the same thing with plots. For example, if you want to add
more data to a line chart:
>>> # Assuming df1 and df2 from the example above still exist...
>>> my_chart = st.line_chart(df1)
>>> time.sleep(1)
>>> my_chart.add_rows(df2)
And for plots whose datasets are named, you can pass the data with a
keyword argument where the key is the name:
>>> my_chart = st.vega_lite_chart(
... {
... "mark": "line",
... "encoding": {"x": "a", "y": "b"},
... "datasets": {
... "some_fancy_name": df1, # <-- named dataset
... },
... "data": {"name": "some_fancy_name"},
... }
... )
>>> my_chart.add_rows(some_fancy_name=df2) # <-- name used as keyword
""" # noqa: E501
show_deprecation_warning(
"`add_rows` is deprecated and might be removed in a future version."
" If you have a specific use-case that requires the `add_rows` "
"functionality, please tell us via this "
"[issue on Github](https://github.com/streamlit/streamlit/issues/13063).",
show_in_browser=False,
)
return _arrow_add_rows(self.dg, data, **kwargs)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
def _prep_data_for_add_rows(
data: Data,
add_rows_metadata: AddRowsMetadata | None,
) -> tuple[Data, AddRowsMetadata | None]:
if not add_rows_metadata:
if dataframe_util.is_pandas_styler(data):
# When calling add_rows on st.table or st.dataframe we want styles to
# pass through.
return data, None
return dataframe_util.convert_anything_to_pandas_df(data), None
# If add_rows_metadata is set, it indicates that the add_rows used called
# on a chart based on our built-in chart commands.
# For built-in chart commands we have to reshape the data structure
# otherwise the input data and the actual data used
# by vega_lite will be different, and it will throw an error.
from streamlit.elements.lib.built_in_chart_utils import prep_chart_data_for_add_rows
return prep_chart_data_for_add_rows(data, add_rows_metadata)
def _arrow_add_rows(
dg: DeltaGenerator,
data: Data = None,
**kwargs: DataFrame | npt.NDArray[Any] | Iterable[Any] | dict[Hashable, Any] | None,
) -> DeltaGenerator | None:
"""Concatenate a dataframe to the bottom of the current one.
Parameters
----------
data : pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, dict, or None
Table to concat. Optional.
**kwargs : pandas.DataFrame, numpy.ndarray, Iterable, dict, or None
The named dataset to concat. Optional. You can only pass in 1
dataset (including the one in the data parameter).
Example
-------
>>> import time
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df1 = pd.DataFrame(
>>> rng(0).standard_normal(size=(50, 20)), columns=("col %d" % i for i in range(20))
>>> )
>>>
>>> df2 = pd.DataFrame(
>>> rng(1).standard_normal(size=(50, 20)), columns=("col %d" % i for i in range(20))
>>> )
>>>
>>> my_table = st.table(df1)
>>> time.sleep(1)
>>> my_table.add_rows(df2)
You can do the same thing with plots. For example, if you want to add
more data to a line chart:
>>> # Assuming df1 and df2 from the example above still exist...
>>> my_chart = st.line_chart(df1)
>>> time.sleep(1)
>>> my_chart.add_rows(df2)
And for plots whose datasets are named, you can pass the data with a
keyword argument where the key is the name:
>>> my_chart = st.vega_lite_chart(
... {
... "mark": "line",
... "encoding": {"x": "a", "y": "b"},
... "datasets": {
... "some_fancy_name": df1, # <-- named dataset
... },
... "data": {"name": "some_fancy_name"},
... }
... )
>>> my_chart.add_rows(some_fancy_name=df2) # <-- name used as keyword
"""
if dg._root_container is None or dg._cursor is None:
return dg
if not dg._cursor.is_locked:
raise StreamlitAPIException("Only existing elements can `add_rows`.")
# Accept syntax st._arrow_add_rows(df).
if data is not None and len(kwargs) == 0:
name = ""
# Accept syntax st._arrow_add_rows(foo=df).
elif len(kwargs) == 1:
name, data = kwargs.popitem()
# Raise error otherwise.
else:
raise StreamlitAPIException(
"Wrong number of arguments to add_rows()."
"Command requires exactly one dataset"
)
# When doing _arrow_add_rows on an element that does not already have data
# (for example, st.line_chart() without any args), call the original
# st.foo() element with new data instead of doing a _arrow_add_rows().
if (
"add_rows_metadata" in dg._cursor.props
and dg._cursor.props["add_rows_metadata"]
and dg._cursor.props["add_rows_metadata"].last_index is None
):
st_method = getattr(dg, dg._cursor.props["add_rows_metadata"].chart_command)
metadata = dg._cursor.props["add_rows_metadata"]
# Pass the styling properties stored in add_rows_metadata
# to the new element call.
kwargs = {}
if metadata.color is not None:
kwargs["color"] = metadata.color
if metadata.width is not None:
kwargs["width"] = metadata.width
if metadata.height is not None:
kwargs["height"] = metadata.height
if metadata.stack is not None:
kwargs["stack"] = metadata.stack
if metadata.chart_command == "bar_chart":
kwargs["horizontal"] = metadata.horizontal
kwargs["sort"] = metadata.sort
if metadata.use_container_width is not None:
kwargs["use_container_width"] = metadata.use_container_width
st_method(data, **kwargs)
return None
new_data, dg._cursor.props["add_rows_metadata"] = _prep_data_for_add_rows(
data,
dg._cursor.props["add_rows_metadata"],
)
msg = ForwardMsg()
msg.metadata.delta_path[:] = dg._cursor.delta_path
default_uuid = str(hash(dg._get_delta_path_str()))
marshall(msg.delta.arrow_add_rows.data, new_data, default_uuid)
if name:
msg.delta.arrow_add_rows.name = name
msg.delta.arrow_add_rows.has_name = True
enqueue_message(msg)
return dg
def marshall(proto: ArrowProto, data: Data, default_uuid: str | None = None) -> None:
"""Marshall pandas.DataFrame into an Arrow proto.
Parameters
----------
proto : proto.Arrow
Output. The protobuf for Streamlit Arrow proto.
data : pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.DataFrame, Iterable, dict, or None
Something that is or can be converted to a dataframe.
default_uuid : str | None
If pandas.Styler UUID is not provided, this value will be used.
This attribute is optional and only used for pandas.Styler, other elements
(e.g. charts) can ignore it.
""" # noqa: E501
if dataframe_util.is_pandas_styler(data):
# default_uuid is a string only if the data is a `Styler`,
# and `None` otherwise.
if not isinstance(default_uuid, str):
raise StreamlitAPIException(
"Default UUID must be a string for Styler data."
)
marshall_styler(proto, data, default_uuid)
proto.data = dataframe_util.convert_anything_to_arrow_bytes(data)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/lib/column_config_utils.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import copy
import json
from collections.abc import Mapping
from enum import Enum
from typing import TYPE_CHECKING, Any, Final, Literal, TypeAlias
from streamlit.dataframe_util import DataFormat
from streamlit.elements.lib.column_types import ColumnConfig, ColumnType
from streamlit.elements.lib.dicttools import remove_none_values
from streamlit.errors import StreamlitAPIException
if TYPE_CHECKING:
import pyarrow as pa
from pandas import DataFrame, Index, Series
from streamlit.proto.Arrow_pb2 import Arrow as ArrowProto
# The index identifier can be used to apply configuration options
IndexIdentifierType = Literal["_index"]
INDEX_IDENTIFIER: IndexIdentifierType = "_index"
# This is used as prefix for columns that are configured via the numerical position.
# The integer value is converted into a string key with this prefix.
# This needs to match with the prefix configured in the frontend.
_NUMERICAL_POSITION_PREFIX = "_pos:"
# The column data kind is used to describe the type of the data within the column.
class ColumnDataKind(str, Enum):
INTEGER = "integer"
FLOAT = "float"
DATE = "date"
TIME = "time"
DATETIME = "datetime"
BOOLEAN = "boolean"
STRING = "string"
TIMEDELTA = "timedelta"
PERIOD = "period"
INTERVAL = "interval"
BYTES = "bytes"
DECIMAL = "decimal"
COMPLEX = "complex"
LIST = "list"
DICT = "dict"
EMPTY = "empty"
UNKNOWN = "unknown"
# The dataframe schema is a mapping from the name of the column
# in the underlying dataframe to the column data kind.
# The index column uses `_index` as name.
DataframeSchema: TypeAlias = dict[str, ColumnDataKind]
# This mapping contains all editable column types mapped to the data kinds
# that the column type is compatible for editing.
_EDITING_COMPATIBILITY_MAPPING: Final[dict[ColumnType, list[ColumnDataKind]]] = {
"text": [ColumnDataKind.STRING, ColumnDataKind.EMPTY],
"number": [
ColumnDataKind.INTEGER,
ColumnDataKind.FLOAT,
ColumnDataKind.DECIMAL,
ColumnDataKind.STRING,
ColumnDataKind.TIMEDELTA,
ColumnDataKind.EMPTY,
],
"checkbox": [
ColumnDataKind.BOOLEAN,
ColumnDataKind.STRING,
ColumnDataKind.INTEGER,
ColumnDataKind.EMPTY,
],
"selectbox": [
ColumnDataKind.STRING,
ColumnDataKind.BOOLEAN,
ColumnDataKind.INTEGER,
ColumnDataKind.FLOAT,
ColumnDataKind.EMPTY,
],
"date": [ColumnDataKind.DATE, ColumnDataKind.DATETIME, ColumnDataKind.EMPTY],
"time": [ColumnDataKind.TIME, ColumnDataKind.DATETIME, ColumnDataKind.EMPTY],
"datetime": [
ColumnDataKind.DATETIME,
ColumnDataKind.DATE,
ColumnDataKind.TIME,
ColumnDataKind.EMPTY,
],
"link": [ColumnDataKind.STRING, ColumnDataKind.EMPTY],
"list": [
ColumnDataKind.LIST,
ColumnDataKind.STRING,
ColumnDataKind.EMPTY,
],
"multiselect": [
ColumnDataKind.LIST,
ColumnDataKind.STRING,
ColumnDataKind.EMPTY,
],
}
def is_type_compatible(column_type: ColumnType, data_kind: ColumnDataKind) -> bool:
"""Check if the column type is compatible with the underlying data kind.
This check only applies to editable column types (e.g. number or text).
Non-editable column types (e.g. bar_chart or image) can be configured for
all data kinds (this might change in the future).
Parameters
----------
column_type : ColumnType
The column type to check.
data_kind : ColumnDataKind
The data kind to check.
Returns
-------
bool
True if the column type is compatible with the data kind, False otherwise.
"""
if column_type not in _EDITING_COMPATIBILITY_MAPPING:
return True
return data_kind in _EDITING_COMPATIBILITY_MAPPING[column_type]
def _determine_data_kind_via_arrow(field: pa.Field) -> ColumnDataKind:
"""Determine the data kind via the arrow type information.
The column data kind refers to the shared data type of the values
in the column (e.g. int, float, str, bool).
Parameters
----------
field : pa.Field
The arrow field from the arrow table schema.
Returns
-------
ColumnDataKind
The data kind of the field.
"""
import pyarrow as pa
field_type = field.type
if pa.types.is_integer(field_type):
return ColumnDataKind.INTEGER
if pa.types.is_floating(field_type):
return ColumnDataKind.FLOAT
if pa.types.is_boolean(field_type):
return ColumnDataKind.BOOLEAN
if pa.types.is_string(field_type):
return ColumnDataKind.STRING
if pa.types.is_date(field_type):
return ColumnDataKind.DATE
if pa.types.is_time(field_type):
return ColumnDataKind.TIME
if pa.types.is_timestamp(field_type):
return ColumnDataKind.DATETIME
if pa.types.is_duration(field_type):
return ColumnDataKind.TIMEDELTA
if pa.types.is_list(field_type):
return ColumnDataKind.LIST
if pa.types.is_decimal(field_type):
return ColumnDataKind.DECIMAL
if pa.types.is_null(field_type):
return ColumnDataKind.EMPTY
# Interval does not seem to work correctly:
# if pa.types.is_interval(field_type):
# return ColumnDataKind.INTERVAL # noqa: ERA001
if pa.types.is_binary(field_type):
return ColumnDataKind.BYTES
if pa.types.is_struct(field_type):
return ColumnDataKind.DICT
return ColumnDataKind.UNKNOWN
def _determine_data_kind_via_pandas_dtype(
column: Series[Any] | Index[Any],
) -> ColumnDataKind:
"""Determine the data kind by using the pandas dtype.
The column data kind refers to the shared data type of the values
in the column (e.g. int, float, str, bool).
Parameters
----------
column : pd.Series, pd.Index
The column for which the data kind should be determined.
Returns
-------
ColumnDataKind
The data kind of the column.
"""
import pandas as pd
column_dtype = column.dtype
if pd.api.types.is_bool_dtype(column_dtype):
return ColumnDataKind.BOOLEAN
if pd.api.types.is_integer_dtype(column_dtype):
return ColumnDataKind.INTEGER
if pd.api.types.is_float_dtype(column_dtype):
return ColumnDataKind.FLOAT
if pd.api.types.is_datetime64_any_dtype(column_dtype):
return ColumnDataKind.DATETIME
if pd.api.types.is_timedelta64_dtype(column_dtype):
return ColumnDataKind.TIMEDELTA
if isinstance(column_dtype, pd.PeriodDtype):
return ColumnDataKind.PERIOD
if isinstance(column_dtype, pd.IntervalDtype):
return ColumnDataKind.INTERVAL
if pd.api.types.is_complex_dtype(column_dtype):
return ColumnDataKind.COMPLEX
if pd.api.types.is_object_dtype(
column_dtype
) is False and pd.api.types.is_string_dtype(column_dtype):
# The is_string_dtype
return ColumnDataKind.STRING
return ColumnDataKind.UNKNOWN
def _determine_data_kind_via_inferred_type(
column: Series[Any] | Index[Any],
) -> ColumnDataKind:
"""Determine the data kind by inferring it from the underlying data.
The column data kind refers to the shared data type of the values
in the column (e.g. int, float, str, bool).
Parameters
----------
column : pd.Series, pd.Index
The column to determine the data kind for.
Returns
-------
ColumnDataKind
The data kind of the column.
"""
from pandas.api.types import infer_dtype
inferred_type = infer_dtype(column)
if inferred_type == "string":
return ColumnDataKind.STRING
if inferred_type == "bytes":
return ColumnDataKind.BYTES
if inferred_type in ["floating", "mixed-integer-float"]:
return ColumnDataKind.FLOAT
if inferred_type == "integer":
return ColumnDataKind.INTEGER
if inferred_type == "decimal":
return ColumnDataKind.DECIMAL
if inferred_type == "complex":
return ColumnDataKind.COMPLEX
if inferred_type == "boolean":
return ColumnDataKind.BOOLEAN
if inferred_type in ["datetime64", "datetime"]:
return ColumnDataKind.DATETIME
if inferred_type == "date":
return ColumnDataKind.DATE
if inferred_type in ["timedelta64", "timedelta"]:
return ColumnDataKind.TIMEDELTA
if inferred_type == "time":
return ColumnDataKind.TIME
if inferred_type == "period":
return ColumnDataKind.PERIOD
if inferred_type == "interval":
return ColumnDataKind.INTERVAL
if inferred_type == "empty":
return ColumnDataKind.EMPTY
# Unused types: mixed, unknown-array, categorical, mixed-integer
return ColumnDataKind.UNKNOWN
def _determine_data_kind(
column: Series[Any] | Index[Any], field: pa.Field | None = None
) -> ColumnDataKind:
"""Determine the data kind of a column.
The column data kind refers to the shared data type of the values
in the column (e.g. int, float, str, bool).
Parameters
----------
column : pd.Series, pd.Index
The column to determine the data kind for.
field : pa.Field, optional
The arrow field from the arrow table schema.
Returns
-------
ColumnDataKind
The data kind of the column.
"""
import pandas as pd
if isinstance(column.dtype, pd.CategoricalDtype):
# Categorical columns can have different underlying data kinds
# depending on the categories.
return _determine_data_kind_via_inferred_type(column.dtype.categories)
if field is not None:
data_kind = _determine_data_kind_via_arrow(field)
if data_kind != ColumnDataKind.UNKNOWN:
return data_kind
if column.dtype.name == "object":
# If dtype is object, we need to infer the type from the column
return _determine_data_kind_via_inferred_type(column)
return _determine_data_kind_via_pandas_dtype(column)
def determine_dataframe_schema(
data_df: DataFrame, arrow_schema: pa.Schema
) -> DataframeSchema:
"""Determine the schema of a dataframe.
Parameters
----------
data_df : pd.DataFrame
The dataframe to determine the schema of.
arrow_schema : pa.Schema
The Arrow schema of the dataframe.
Returns
-------
DataframeSchema
A mapping that contains the detected data type for the index and columns.
The key is the column name in the underlying dataframe or ``_index`` for index columns.
"""
dataframe_schema: DataframeSchema = {}
# Add type of index:
# TODO(lukasmasuch): We need to apply changes here to support multiindex.
dataframe_schema[INDEX_IDENTIFIER] = _determine_data_kind(data_df.index)
# Add types for all columns:
for i, column in enumerate(data_df.items()):
column_name = str(column[0])
column_data = column[1]
dataframe_schema[column_name] = _determine_data_kind(
column_data, arrow_schema.field(i)
)
return dataframe_schema
# A mapping of column names/IDs to column configs.
ColumnConfigMapping: TypeAlias = dict[IndexIdentifierType | str | int, ColumnConfig]
ColumnConfigMappingInput: TypeAlias = Mapping[
# TODO(lukasmasuch): This should also use int here to
# correctly type the support for positional index. However,
# allowing int here leads mypy to complain about simple dict[str, ...]
# as input -> which seems like a mypy bug.
IndexIdentifierType | str,
ColumnConfig | None | str,
]
def process_config_mapping(
column_config: ColumnConfigMappingInput | None = None,
) -> ColumnConfigMapping:
"""Transforms a user-provided column config mapping into a valid column config mapping
that can be used by the frontend.
Parameters
----------
column_config: dict or None
The user-provided column config mapping.
Returns
-------
dict
The transformed column config mapping.
"""
if column_config is None:
return {}
transformed_column_config: ColumnConfigMapping = {}
for column, config in column_config.items():
if config is None:
transformed_column_config[column] = ColumnConfig(hidden=True)
elif isinstance(config, str):
transformed_column_config[column] = ColumnConfig(label=config)
elif isinstance(config, dict):
# Ensure that the column config objects are cloned
# since we will apply in-place changes to it.
transformed_column_config[column] = copy.deepcopy(config)
else:
raise StreamlitAPIException(
f"Invalid column config for column `{column}`. "
f"Expected `None`, `str` or `dict`, but got `{type(config)}`."
)
return transformed_column_config
def update_column_config(
column_config_mapping: ColumnConfigMapping,
column: str | int,
column_config: ColumnConfig,
) -> None:
"""Updates the column config value for a single column within the mapping.
Parameters
----------
column_config_mapping : ColumnConfigMapping
The column config mapping to update.
column : str | int
The column to update the config value for. This can be the column name or
the numerical position of the column.
column_config : ColumnConfig
The column config to update.
"""
if column not in column_config_mapping:
column_config_mapping[column] = {}
column_config_mapping[column].update(column_config)
def apply_data_specific_configs(
columns_config: ColumnConfigMapping,
data_format: DataFormat,
) -> None:
"""Apply data specific configurations to the provided dataframe.
This will apply inplace changes to the dataframe and the column configurations
depending on the data format.
Parameters
----------
columns_config : ColumnConfigMapping
A mapping of column names/ids to column configurations.
data_format : DataFormat
The format of the data.
"""
# Pandas adds a range index as default to all datastructures
# but for most of the non-pandas data objects it is unnecessary
# to show this index to the user. Therefore, we will hide it as default.
if data_format in [
DataFormat.SET_OF_VALUES,
DataFormat.TUPLE_OF_VALUES,
DataFormat.LIST_OF_VALUES,
DataFormat.NUMPY_LIST,
DataFormat.NUMPY_MATRIX,
DataFormat.LIST_OF_RECORDS,
DataFormat.LIST_OF_ROWS,
DataFormat.COLUMN_VALUE_MAPPING,
# Dataframe-like objects that don't have an index:
DataFormat.PANDAS_ARRAY,
DataFormat.PANDAS_INDEX,
DataFormat.POLARS_DATAFRAME,
DataFormat.POLARS_SERIES,
DataFormat.POLARS_LAZYFRAME,
DataFormat.PYARROW_ARRAY,
DataFormat.RAY_DATASET,
]:
update_column_config(columns_config, INDEX_IDENTIFIER, {"hidden": True})
def _convert_column_config_to_json(column_config_mapping: ColumnConfigMapping) -> str:
try:
# Ignore all None values and prefix columns specified by numerical index:
return json.dumps(
{
(f"{_NUMERICAL_POSITION_PREFIX}{k!s}" if isinstance(k, int) else k): v
for (k, v) in remove_none_values(column_config_mapping).items()
},
allow_nan=False,
)
except ValueError as ex:
raise StreamlitAPIException(
f"The provided column config cannot be serialized into JSON: {ex}"
) from ex
def marshall_column_config(
proto: ArrowProto, column_config_mapping: ColumnConfigMapping
) -> None:
"""Marshall the column config into the Arrow proto.
Parameters
----------
proto : ArrowProto
The proto to marshall into.
column_config_mapping : ColumnConfigMapping
The column config to marshall.
"""
proto.columns = _convert_column_config_to_json(column_config_mapping)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/lib/__init__.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/lib/js_number.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import numbers
class JSNumberBoundsException(Exception): # noqa: N818
pass
class JSNumber:
"""Utility class for exposing JavaScript Number constants."""
# The largest int that can be represented with perfect precision
# in JavaScript.
MAX_SAFE_INTEGER = (1 << 53) - 1
# The smallest int that can be represented with perfect precision
# in JavaScript.
MIN_SAFE_INTEGER = -((1 << 53) - 1)
# The largest float that can be represented in JavaScript.
MAX_VALUE = 1.7976931348623157e308
# The closest number to zero that can be represented in JavaScript.
MIN_VALUE = 5e-324
# The largest negative float that can be represented in JavaScript.
MIN_NEGATIVE_VALUE = -MAX_VALUE
@classmethod
def validate_int_bounds(cls, value: int, value_name: str | None = None) -> None:
"""Validate that an int value can be represented with perfect precision
by a JavaScript Number.
Parameters
----------
value : int
value_name : str or None
The name of the value parameter. If specified, this will be used
in any exception that is thrown.
Raises
------
JSNumberBoundsException
Raised with a human-readable explanation if the value falls outside
JavaScript int bounds.
"""
if value_name is None:
value_name = "value"
if value < cls.MIN_SAFE_INTEGER:
raise JSNumberBoundsException(
f"{value_name} ({value}) must be >= -((1 << 53) - 1)"
)
if value > cls.MAX_SAFE_INTEGER:
raise JSNumberBoundsException(
f"{value_name} ({value}) must be <= (1 << 53) - 1"
)
@classmethod
def validate_float_bounds(cls, value: int | float, value_name: str | None) -> None:
"""Validate that a float value can be represented by a JavaScript Number.
Parameters
----------
value : float
value_name : str or None
The name of the value parameter. If specified, this will be used
in any exception that is thrown.
Raises
------
JSNumberBoundsException
Raised with a human-readable explanation if the value falls outside
JavaScript float bounds.
"""
if value_name is None:
value_name = "value"
if not isinstance(value, (numbers.Integral, float)):
raise JSNumberBoundsException(f"{value_name} ({value}) is not a float")
if value < cls.MIN_NEGATIVE_VALUE:
raise JSNumberBoundsException(
f"{value_name} ({value}) must be >= -1.797e+308"
)
if value > cls.MAX_VALUE:
raise JSNumberBoundsException(
f"{value_name} ({value}) must be <= 1.797e+308"
)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/lib/file_uploader_utils.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import os
from typing import TYPE_CHECKING
from streamlit.errors import StreamlitAPIException
if TYPE_CHECKING:
from collections.abc import Sequence
TYPE_PAIRS = [
(".jpg", ".jpeg"),
(".mpg", ".mpeg"),
(".mp4", ".mpeg4"),
(".tif", ".tiff"),
(".htm", ".html"),
]
def _get_main_filename_and_extension(filename: str) -> tuple[str, str]:
"""Returns the main part of a filename and its extension."""
# Handle NTFS Alternate Data Streams (ADS) on Windows, e.g: "file.txt:ads" -> ("file.txt", ".txt")
if os.name == "nt" and ":" in filename:
main_filename, ads_part = filename.split(":", 1)
# We only treat it as an ADS if the part after the colon has an extension.
if os.path.splitext(ads_part)[1]:
return main_filename, os.path.splitext(main_filename)[1]
return filename, os.path.splitext(filename)[1]
def normalize_upload_file_type(file_type: str | Sequence[str]) -> Sequence[str]:
if isinstance(file_type, str):
file_type = [file_type]
# May need a regex or a library to validate file types are valid
# extensions.
file_type = [
file_type_entry if file_type_entry[0] == "." else f".{file_type_entry}"
for file_type_entry in file_type
]
file_type = [t.lower() for t in file_type]
for x, y in TYPE_PAIRS:
if x in file_type and y not in file_type:
file_type.append(y)
if y in file_type and x not in file_type:
file_type.append(x)
return file_type
def enforce_filename_restriction(filename: str, allowed_types: Sequence[str]) -> None:
"""Ensure the uploaded file's extension matches the allowed
types set by the app developer. In theory, this should never happen, since we
enforce file type check by extension on the frontend, but we check it on backend
before returning file to the user to protect ourselves.
"""
# Ensure that there isn't a null byte in a filename
# since this could be a workaround to bypass the file type check.
if "\0" in filename:
raise StreamlitAPIException("Filename cannot contain null bytes.")
main_filename, extension = _get_main_filename_and_extension(filename)
normalized_filename = main_filename.lower()
normalized_allowed_types = [allowed_type.lower() for allowed_type in allowed_types]
if not any(
normalized_filename.endswith(allowed_type)
for allowed_type in normalized_allowed_types
):
raise StreamlitAPIException(
f"Invalid file extension: `{extension}`. Allowed: {allowed_types}"
)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/lib/image_utils.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import io
import os
import re
from collections.abc import Sequence
from enum import IntEnum
from pathlib import Path
from typing import TYPE_CHECKING, Final, Literal, TypeAlias, Union, cast
from streamlit import runtime, url_util
from streamlit.errors import StreamlitAPIException
from streamlit.runtime import caching
if TYPE_CHECKING:
from typing import Any
import numpy.typing as npt
from PIL import GifImagePlugin, Image, ImageFile
from streamlit.elements.lib.layout_utils import LayoutConfig
from streamlit.proto.Image_pb2 import ImageList as ImageListProto
from streamlit.type_util import NumpyShape
PILImage: TypeAlias = Union[
"ImageFile.ImageFile", "Image.Image", "GifImagePlugin.GifImageFile"
]
AtomicImage: TypeAlias = Union[
PILImage, "npt.NDArray[Any]", io.BytesIO, str, Path, bytes
]
Channels: TypeAlias = Literal["RGB", "BGR"]
ImageFormat: TypeAlias = Literal["JPEG", "PNG", "GIF"]
ImageFormatOrAuto: TypeAlias = Literal[ImageFormat, "auto"]
ImageOrImageList: TypeAlias = AtomicImage | Sequence[AtomicImage]
# This constant is related to the frontend maximum content width specified
# in App.jsx main container
# 730 is the max width of element-container in the frontend, and 2x is for high
# DPI.
MAXIMUM_CONTENT_WIDTH: Final[int] = 2 * 730
# @see Image.proto
# @see WidthBehavior on the frontend
class WidthBehavior(IntEnum):
"""
Special values that are recognized by the frontend and allow us to change the
behavior of the displayed image.
"""
ORIGINAL = -1
COLUMN = -2
AUTO = -3
MIN_IMAGE_OR_CONTAINER = -4
MAX_IMAGE_OR_CONTAINER = -5
WidthBehavior.ORIGINAL.__doc__ = """Display the image at its original width"""
WidthBehavior.COLUMN.__doc__ = (
"""Display the image at the width of the column it's in."""
)
WidthBehavior.AUTO.__doc__ = """Display the image at its original width, unless it
would exceed the width of its column in which case clamp it to
its column width"""
def _image_may_have_alpha_channel(image: PILImage) -> bool:
return image.mode in ("RGBA", "LA", "P")
def _image_is_gif(image: PILImage) -> bool:
return image.format == "GIF"
def _validate_image_format_string(
image_data: bytes | PILImage, format: str
) -> ImageFormat:
"""Return either "JPEG", "PNG", or "GIF", based on the input `format` string.
- If `format` is "JPEG" or "JPG" (or any capitalization thereof), return "JPEG"
- If `format` is "PNG" (or any capitalization thereof), return "PNG"
- For all other strings, return "PNG" if the image has an alpha channel,
"GIF" if the image is a GIF, and "JPEG" otherwise.
"""
img_format = format.upper()
if img_format in {"JPEG", "PNG"}:
return cast("ImageFormat", img_format)
# We are forgiving on the spelling of JPEG
if img_format == "JPG":
return "JPEG"
pil_image: PILImage
if isinstance(image_data, bytes):
from PIL import Image
pil_image = Image.open(io.BytesIO(image_data))
else:
pil_image = image_data
if _image_is_gif(pil_image):
return "GIF"
if _image_may_have_alpha_channel(pil_image):
return "PNG"
return "JPEG"
def _pil_to_bytes(
image: PILImage,
format: ImageFormat = "JPEG",
quality: int = 100,
) -> bytes:
"""Convert a PIL image to bytes."""
tmp = io.BytesIO()
# User must have specified JPEG, so we must convert it
if format == "JPEG" and _image_may_have_alpha_channel(image):
image = image.convert("RGB")
image.save(tmp, format=format, quality=quality)
return tmp.getvalue()
def _bytesio_to_bytes(data: io.BytesIO) -> bytes:
data.seek(0)
return data.getvalue()
def _np_array_to_bytes(array: npt.NDArray[Any], output_format: str = "JPEG") -> bytes:
import numpy as np
from PIL import Image
img = Image.fromarray(array.astype(np.uint8))
img_format = _validate_image_format_string(img, output_format)
return _pil_to_bytes(img, img_format)
def _verify_np_shape(array: npt.NDArray[Any]) -> npt.NDArray[Any]:
shape: NumpyShape = array.shape
if len(shape) not in (2, 3):
raise StreamlitAPIException("Numpy shape has to be of length 2 or 3.")
if len(shape) == 3 and shape[-1] not in (1, 3, 4):
raise StreamlitAPIException(
f"Channel can only be 1, 3, or 4 got {shape[-1]}. Shape is {shape}"
)
# If there's only one channel, convert is to x, y
if len(shape) == 3 and shape[-1] == 1:
array = array[:, :, 0]
return array
def _get_image_format_mimetype(image_format: ImageFormat) -> str:
"""Get the mimetype string for the given ImageFormat."""
return f"image/{image_format.lower()}"
def _ensure_image_size_and_format(
image_data: bytes, layout_config: LayoutConfig, image_format: ImageFormat
) -> bytes:
"""Resize an image if it exceeds the given width, or if exceeds
MAXIMUM_CONTENT_WIDTH. Ensure the image's format corresponds to the given
ImageFormat. Return the (possibly resized and reformatted) image bytes.
"""
from PIL import Image
pil_image: PILImage = Image.open(io.BytesIO(image_data))
actual_width, actual_height = pil_image.size
target_width = (
layout_config.width
if isinstance(layout_config.width, int)
else MAXIMUM_CONTENT_WIDTH
)
# Resizing the image down if the embedded width is greater than
# the target width.
if target_width > 0 and actual_width > target_width:
# We need to resize the image.
new_height = int(1.0 * actual_height * target_width / actual_width)
# pillow reexports Image.Resampling.BILINEAR as Image.BILINEAR for backwards
# compatibility reasons, so we use the reexport to support older pillow
# versions. The types don't seem to reflect this, though, hence the type: ignore
# below.
pil_image = pil_image.resize(
(target_width, new_height),
resample=Image.BILINEAR, # type: ignore[attr-defined]
)
return _pil_to_bytes(pil_image, format=image_format, quality=90)
if pil_image.format != image_format:
# We need to reformat the image.
return _pil_to_bytes(pil_image, format=image_format, quality=90)
# No resizing or reformatting necessary - return the original bytes.
return image_data
def _clip_image(image: npt.NDArray[Any], clamp: bool) -> npt.NDArray[Any]:
import numpy as np
data = image
if issubclass(image.dtype.type, np.floating):
if clamp:
data = np.clip(image, 0, 1.0)
elif np.amin(image) < 0.0 or np.amax(image) > 1.0:
raise RuntimeError("Data is outside [0.0, 1.0] and clamp is not set.")
data = data * 255
elif clamp:
data = np.clip(image, 0, 255)
elif np.amin(image) < 0 or np.amax(image) > 255:
raise RuntimeError("Data is outside [0, 255] and clamp is not set.")
return data
def image_to_url(
image: AtomicImage,
layout_config: LayoutConfig,
clamp: bool,
channels: Channels,
output_format: ImageFormatOrAuto,
image_id: str,
) -> str:
"""Return a URL that an image can be served from.
If `image` is already a URL, return it unmodified.
Otherwise, add the image to the MediaFileManager and return the URL.
(When running in "raw" mode, we won't actually load data into the
MediaFileManager, and we'll return an empty URL).
"""
import numpy as np
from PIL import Image, ImageFile
image_data: bytes
# Convert Path to string if necessary
if isinstance(image, Path):
image = str(image)
# Strings
if isinstance(image, str):
if not os.path.isfile(image) and url_util.is_url(
image, allowed_schemas=("http", "https", "data")
):
# If it's a url, return it directly.
return image
if image.endswith(".svg") and os.path.isfile(image):
# Unpack local SVG image file to an SVG string
with open(image) as textfile:
image = textfile.read()
# Following regex allows svg image files to start either via a "<?xml...>" tag
# eventually followed by a "<svg...>" tag or directly starting with a "<svg>" tag
if re.search(r"(^\s?(<\?xml[\s\S]*<svg\s)|^\s?<svg\s|^\s?<svg>\s)", image):
if "xmlns" not in image:
# The xmlns attribute is required for SVGs to render in an img tag.
# If it's not present, we add to the first SVG tag:
image = image.replace(
"<svg", '<svg xmlns="http://www.w3.org/2000/svg" ', 1
)
# Convert to base64 to prevent issues with encoding:
import base64
image_b64_encoded = base64.b64encode(image.encode("utf-8")).decode("utf-8")
# Return SVG as data URI:
return f"data:image/svg+xml;base64,{image_b64_encoded}"
# Otherwise, try to open it as a file.
try:
with open(image, "rb") as f:
image_data = f.read()
except Exception:
# When we aren't able to open the image file, we still pass the path to
# the MediaFileManager - its storage backend may have access to files
# that Streamlit does not.
import mimetypes
mimetype, _ = mimetypes.guess_type(image)
if mimetype is None:
mimetype = "application/octet-stream"
url = runtime.get_instance().media_file_mgr.add(image, mimetype, image_id)
caching.save_media_data(image, mimetype, image_id)
return url
# PIL Images
elif isinstance(image, (ImageFile.ImageFile, Image.Image)):
img_format = _validate_image_format_string(image, output_format)
image_data = _pil_to_bytes(image, img_format)
# BytesIO
# Note: This doesn't support SVG. We could convert to png (cairosvg.svg2png)
# or just decode BytesIO to string and handle that way.
elif isinstance(image, io.BytesIO):
image_data = _bytesio_to_bytes(image)
# Numpy Arrays (ie opencv)
elif isinstance(image, np.ndarray):
image = _clip_image(_verify_np_shape(image), clamp)
if channels == "BGR":
if len(image.shape) == 3:
image = image[:, :, [2, 1, 0]]
else:
raise StreamlitAPIException(
'When using `channels="BGR"`, the input image should '
"have exactly 3 color channels"
)
image_data = _np_array_to_bytes(array=image, output_format=output_format)
# Raw bytes
else:
image_data = image
# Determine the image's format, resize it, and get its mimetype
image_format = _validate_image_format_string(image_data, output_format)
image_data = _ensure_image_size_and_format(image_data, layout_config, image_format)
mimetype = _get_image_format_mimetype(image_format)
if runtime.exists():
url = runtime.get_instance().media_file_mgr.add(image_data, mimetype, image_id)
caching.save_media_data(image_data, mimetype, image_id)
return url
# When running in "raw mode", we can't access the MediaFileManager.
return ""
def _4d_to_list_3d(array: npt.NDArray[Any]) -> list[npt.NDArray[Any]]:
return [array[i, :, :, :] for i in range(array.shape[0])]
def marshall_images(
coordinates: str,
image: ImageOrImageList,
caption: str | npt.NDArray[Any] | list[str] | None,
layout_config: LayoutConfig,
proto_imgs: ImageListProto,
clamp: bool,
channels: Channels = "RGB",
output_format: ImageFormatOrAuto = "auto",
) -> None:
"""Fill an ImageListProto with a list of images and their captions.
The images will be resized and reformatted as necessary.
Parameters
----------
coordinates
A string identifying the images' location in the frontend.
image
The image or images to include in the ImageListProto.
caption
Image caption. If displaying multiple images, caption should be a
list of captions (one for each image).
width
The desired width of the image or images. This parameter will be
passed to the frontend.
Positive values set the image width explicitly.
Negative values has some special. For details, see: `WidthBehaviour`
proto_imgs
The ImageListProto to fill in.
clamp
Clamp image pixel values to a valid range ([0-255] per channel).
This is only meaningful for byte array images; the parameter is
ignored for image URLs. If this is not set, and an image has an
out-of-range value, an error will be thrown.
channels
If image is an nd.array, this parameter denotes the format used to
represent color information. Defaults to 'RGB', meaning
`image[:, :, 0]` is the red channel, `image[:, :, 1]` is green, and
`image[:, :, 2]` is blue. For images coming from libraries like
OpenCV you should set this to 'BGR', instead.
output_format
This parameter specifies the format to use when transferring the
image data. Photos should use the JPEG format for lossy compression
while diagrams should use the PNG format for lossless compression.
Defaults to 'auto' which identifies the compression type based
on the type and format of the image argument.
"""
import numpy as np
channels = cast("Channels", channels.upper())
# Turn single image and caption into one element list.
images: Sequence[AtomicImage]
if isinstance(image, (list, set, tuple)):
images = list(image)
elif isinstance(image, np.ndarray) and len(image.shape) == 4:
images = _4d_to_list_3d(image)
else:
images = cast("Sequence[AtomicImage]", [image])
if isinstance(caption, list):
captions: Sequence[str | None] = caption
elif isinstance(caption, str):
captions = [caption]
elif isinstance(caption, np.ndarray) and len(caption.shape) == 1:
captions = caption.tolist()
elif caption is None:
captions = [None] * len(images)
else:
captions = [str(caption)]
if not isinstance(captions, list):
raise StreamlitAPIException(
"If image is a list then caption should be a list as well."
)
if len(captions) != len(images):
raise StreamlitAPIException(
f"Cannot pair {len(captions)} captions with {len(images)} images."
)
# Each image in an image list needs to be kept track of at its own coordinates.
for coord_suffix, (single_image, single_caption) in enumerate(
zip(images, captions, strict=False)
):
proto_img = proto_imgs.imgs.add()
if single_caption is not None:
proto_img.caption = str(single_caption)
# We use the index of the image in the input image list to identify this image inside
# MediaFileManager. For this, we just add the index to the image's "coordinates".
image_id = f"{coordinates}-{coord_suffix}"
proto_img.url = image_to_url(
single_image, layout_config, clamp, channels, output_format, image_id
)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/lib/policies.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Final
from streamlit import config, errors, logger, runtime
from streamlit.elements.lib.form_utils import is_in_form
from streamlit.errors import (
StreamlitAPIWarning,
StreamlitFragmentWidgetsNotAllowedOutsideError,
StreamlitInvalidFormCallbackError,
StreamlitValueAssignmentNotAllowedError,
)
from streamlit.runtime.scriptrunner_utils.script_run_context import (
get_script_run_ctx,
in_cached_function,
)
from streamlit.runtime.state import WidgetCallback, get_session_state
if TYPE_CHECKING:
from collections.abc import Sequence
from streamlit.delta_generator import DeltaGenerator
_LOGGER: Final = logger.get_logger(__name__)
def check_callback_rules(dg: DeltaGenerator, on_change: WidgetCallback | None) -> None:
"""Ensures that widgets other than `st.form_submit_button` within a form don't have
an on_change callback set.
Raises
------
StreamlitInvalidFormCallbackError:
Raised when the described rule is violated.
"""
if runtime.exists() and is_in_form(dg) and on_change is not None:
raise StreamlitInvalidFormCallbackError()
_shown_default_value_warning: bool = False
def check_session_state_rules(
default_value: Any, key: str | None, writes_allowed: bool = True
) -> None:
"""Ensures that no values are set for widgets with the given key when writing
is not allowed.
Additionally, if `global.disableWidgetStateDuplicationWarning` is False a warning is
shown when a widget has a default value but its value is also set via session state.
Raises
------
StreamlitAPIException:
Raised when the described rule is violated.
"""
global _shown_default_value_warning # noqa: PLW0603
if key is None or not runtime.exists():
return
session_state = get_session_state()
if not session_state.is_new_state_value(key):
return
if not writes_allowed:
raise StreamlitValueAssignmentNotAllowedError(key=key)
if (
default_value is not None
and not _shown_default_value_warning
and not config.get_option("global.disableWidgetStateDuplicationWarning")
):
from streamlit import warning
warning(
f'The widget with key "{key}" was created with a default value but'
" also had its value set via the Session State API."
)
_shown_default_value_warning = True
class CachedWidgetWarning(StreamlitAPIWarning):
def __init__(self) -> None:
super().__init__(
"""
Your script uses a widget command in a cached function
(function decorated with `@st.cache_data` or `@st.cache_resource`).
This code will only be called when we detect a cache "miss",
which can lead to unexpected results.
To fix this, move all widget commands outside the cached function.
"""
)
def check_cache_replay_rules() -> None:
"""Check if a widget is allowed to be used in the current context.
More specifically, this checks if the current context is inside a
cached function that disallows widget usage. If so, it raises a warning.
If there are other similar checks in the future, we could extend this
function to check for those as well. And rename it to check_widget_usage_rules.
"""
if in_cached_function.get():
from streamlit import exception
# We use an exception here to show a proper stack trace
# that indicates to the user where the issue is.
exception(CachedWidgetWarning())
def check_fragment_path_policy(dg: DeltaGenerator) -> None:
"""Ensures that the current widget is not written outside of the
fragment's delta path.
Should be called by ever element that acts as a widget.
We don't allow writing widgets from within a widget to the outside path
because it can lead to unexpected behavior. For elements, this is okay
because they do not trigger a re-run.
"""
ctx = get_script_run_ctx()
# Check is only relevant for fragments
if ctx is None or ctx.current_fragment_id is None:
return
current_fragment_delta_path = ctx.current_fragment_delta_path
current_cursor = dg._active_dg._cursor
if current_cursor is None:
return
current_cursor_delta_path = current_cursor.delta_path
# the elements delta path cannot be smaller than the fragment's delta path if it is
# inside of the fragment
if len(current_cursor_delta_path) < len(current_fragment_delta_path):
raise StreamlitFragmentWidgetsNotAllowedOutsideError()
# all path indices of the fragment-path must occur in the inner-elements delta path,
# otherwise it is outside of the fragment container
for index, path_index in enumerate(current_fragment_delta_path):
if current_cursor_delta_path[index] != path_index:
raise StreamlitFragmentWidgetsNotAllowedOutsideError()
def check_widget_policies(
dg: DeltaGenerator,
key: str | None,
on_change: WidgetCallback | None = None,
*,
default_value: Sequence[Any] | Any | None = None,
writes_allowed: bool = True,
enable_check_callback_rules: bool = True,
) -> None:
"""Check all widget policies for the given DeltaGenerator."""
check_fragment_path_policy(dg)
check_cache_replay_rules()
if enable_check_callback_rules:
check_callback_rules(dg, on_change)
check_session_state_rules(
default_value=default_value, key=key, writes_allowed=writes_allowed
)
def maybe_raise_label_warnings(label: str | None, label_visibility: str | None) -> None:
if not label:
_LOGGER.warning(
"`label` got an empty value. This is discouraged for accessibility "
"reasons and may be disallowed in the future by raising an exception. "
"Please provide a non-empty label and hide it with label_visibility "
"if needed.",
stack_info=True,
)
if label_visibility not in ("visible", "hidden", "collapsed"):
raise errors.StreamlitAPIException(
f"Unsupported label_visibility option '{label_visibility}'. "
f"Valid values are 'visible', 'hidden' or 'collapsed'."
)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/lib/built_in_chart_utils.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
"""Utilities for our built-in charts commands."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from enum import Enum
from typing import TYPE_CHECKING, Any, Final, Literal, TypeAlias, TypedDict, cast
from streamlit import dataframe_util, type_util
from streamlit.elements.lib.color_util import (
Color,
is_color_like,
is_color_tuple_like,
is_hex_color_like,
to_css_color,
)
from streamlit.errors import Error, StreamlitAPIException
if TYPE_CHECKING:
from collections.abc import Collection, Hashable, Sequence
import altair as alt
import pandas as pd
from streamlit.dataframe_util import Data
from streamlit.elements.lib.layout_utils import (
Height,
Width,
)
VegaLiteType: TypeAlias = Literal["quantitative", "ordinal", "temporal", "nominal"]
ChartStackType: TypeAlias = Literal["normalize", "center", "layered"]
# Threshold for applying hover event throttling on large datasets.
# For datasets with more points than this threshold, hover events are throttled
# to 16ms (~60fps) to improve performance.
_LARGE_DATASET_POINT_THRESHOLD: Final = 1000
class PrepDataColumns(TypedDict):
"""Columns used for the prep_data step in Altair Arrow charts."""
x_column: str | None
y_column_list: list[str]
color_column: str | None
size_column: str | None
sort_column: str | None
@dataclass
class AddRowsMetadata:
"""Metadata needed by add_rows on native charts.
This class is used to pass some important info to add_rows.
"""
chart_command: str
last_index: Hashable | None
columns: PrepDataColumns
# Chart styling properties
color: str | Color | list[Color] | None = None
width: Width | None = None
height: Height | None = None
use_container_width: bool | None = None
# Only applicable for bar & area charts
stack: bool | ChartStackType | None = None
# Only applicable for bar charts
horizontal: bool = False
sort: bool | str = False
class ChartType(Enum):
AREA: Final = {"mark_type": "area", "command": "area_chart"}
VERTICAL_BAR: Final = {
"mark_type": "bar",
"command": "bar_chart",
"horizontal": False,
}
HORIZONTAL_BAR: Final = {
"mark_type": "bar",
"command": "bar_chart",
"horizontal": True,
}
LINE: Final = {"mark_type": "line", "command": "line_chart"}
SCATTER: Final = {"mark_type": "circle", "command": "scatter_chart"}
# Color and size legends need different title paddings in order for them
# to be vertically aligned.
#
# NOTE: I don't think it's possible to *perfectly* align the size and
# color legends in all instances, since the "size" circles vary in size based
# on the data, and their container is top-aligned with the color container. But
# through trial-and-error I found this value to be a good enough middle ground.
#
# NOTE #2: In theory, we could move COLOR_LEGEND_SETTINGS into
# ArrowVegaLiteChart/CustomTheme.tsx, but this would impact existing behavior.
# (See https://github.com/streamlit/streamlit/pull/7164#discussion_r1307707345)
_COLOR_LEGEND_SETTINGS: Final = {"titlePadding": 5, "offset": 5, "orient": "bottom"}
_SIZE_LEGEND_SETTINGS: Final = {"titlePadding": 0.5, "offset": 5, "orient": "bottom"}
# User-readable names to give the index and melted columns.
_SEPARATED_INDEX_COLUMN_TITLE: Final = "index"
_MELTED_Y_COLUMN_TITLE: Final = "value"
_MELTED_COLOR_COLUMN_TITLE: Final = "color"
# Crazy internal (non-user-visible) names for the index and melted columns, in order to
# avoid collision with existing column names.
_PROTECTION_SUFFIX: Final = " -- streamlit-generated"
_SEPARATED_INDEX_COLUMN_NAME: Final = _SEPARATED_INDEX_COLUMN_TITLE + _PROTECTION_SUFFIX
_MELTED_Y_COLUMN_NAME: Final = _MELTED_Y_COLUMN_TITLE + _PROTECTION_SUFFIX
_MELTED_COLOR_COLUMN_NAME: Final = _MELTED_COLOR_COLUMN_TITLE + _PROTECTION_SUFFIX
# Name we use for a column we know doesn't exist in the data, to address a Vega-Lite
# rendering bug
# where empty charts need x, y encodings set in order to take up space.
_NON_EXISTENT_COLUMN_NAME: Final = "DOES_NOT_EXIST" + _PROTECTION_SUFFIX
def maybe_raise_stack_warning(
stack: bool | ChartStackType | None, command: str | None, docs_link: str
) -> None:
# Check that the stack parameter is valid, raise more informative error if not
if stack not in (None, True, False, "normalize", "center", "layered"):
raise StreamlitAPIException(
f"Invalid value for stack parameter: {stack}. Stack must be one of True, "
'False, "normalize", "center", "layered" or None. See documentation '
f"for `{command}` [here]({docs_link}) for more information."
)
def generate_chart(
chart_type: ChartType,
data: Data | None,
x_from_user: str | None = None,
y_from_user: str | Sequence[str] | None = None,
x_axis_label: str | None = None,
y_axis_label: str | None = None,
color_from_user: str | Color | list[Color] | None = None,
size_from_user: str | float | None = None,
width: Width | None = None,
height: Height | None = None,
use_container_width: bool | None = None,
# Bar & Area charts only:
stack: bool | ChartStackType | None = None,
# Bar charts only:
horizontal: bool = False,
sort_from_user: bool | str = False,
) -> tuple[alt.Chart | alt.LayerChart, AddRowsMetadata]:
"""Function to use the chart's type, data columns and indices to figure out the
chart's spec.
"""
import altair as alt
df = dataframe_util.convert_anything_to_pandas_df(data, ensure_copy=True)
# From now on, use "df" instead of "data". Deleting "data" to guarantee we follow
# this.
del data
# Convert arguments received from the user to things Vega-Lite understands.
# Get name of column to use for x.
x_column = _parse_x_column(df, x_from_user)
# Get name of columns to use for y.
y_column_list = _parse_y_columns(df, y_from_user, x_column)
# Get name of column to use for color, or constant value to use. Any/both could
# be None.
color_column, color_value = _parse_generic_column(df, color_from_user)
# Get name of column to use for size, or constant value to use. Any/both could
# be None.
size_column, size_value = _parse_generic_column(df, size_from_user)
# Get name of column to use for sort.
sort_column = _parse_sort_column(df, sort_from_user)
# Store some info so we can use it in add_rows.
add_rows_metadata = AddRowsMetadata(
# The st command that was used to generate this chart.
chart_command=chart_type.value["command"],
# The last index of df so we can adjust the input df in add_rows:
last_index=_last_index_for_melted_dataframes(df),
# This is the input to prep_data (except for the df):
columns={
"x_column": x_column,
"y_column_list": y_column_list,
"color_column": color_column,
"size_column": size_column,
"sort_column": sort_column,
},
# Chart styling properties
color=color_from_user,
width=width,
height=height,
use_container_width=use_container_width,
stack=stack,
horizontal=horizontal,
sort=sort_from_user,
)
# At this point, all foo_column variables are either None/empty or contain actual
# columns that are guaranteed to exist.
df, x_column, y_column, color_column, size_column, sort_column = _prep_data(
df, x_column, y_column_list, color_column, size_column, sort_column
)
# At this point, x_column is only None if user did not provide one AND df is empty.
# Get x and y encodings
x_encoding, y_encoding = _get_axis_encodings(
df,
chart_type,
x_column,
y_column,
x_from_user,
y_from_user,
x_axis_label,
y_axis_label,
stack,
sort_from_user,
)
chart_width = width if isinstance(width, int) else None
chart_height = height if isinstance(height, int) else None
# Create a Chart with x and y encodings.
chart = alt.Chart(
data=df,
mark=chart_type.value["mark_type"],
width=chart_width or 0,
height=chart_height or 0,
).encode(
x=x_encoding,
y=y_encoding,
)
# Offset encoding only works for Altair >= 5.0.0
is_altair_version_5_or_greater = not type_util.is_altair_version_less_than("5.0.0")
# Set up offset encoding (creates grouped/non-stacked bar charts, so only applicable
# when stack=False).
if is_altair_version_5_or_greater and stack is False and color_column is not None:
x_offset, y_offset = _get_offset_encoding(chart_type, color_column)
chart = chart.encode(xOffset=x_offset, yOffset=y_offset)
# Set up opacity encoding.
opacity_enc = _get_opacity_encoding(chart_type, stack, color_column)
if opacity_enc is not None:
chart = chart.encode(opacity=opacity_enc)
# Set up color encoding.
color_enc = _get_color_encoding(
df, color_value, color_column, y_column_list, color_from_user
)
if color_enc is not None:
chart = chart.encode(color=color_enc)
# Set up size encoding.
size_enc = _get_size_encoding(chart_type, size_column, size_value)
if size_enc is not None:
chart = chart.encode(size=size_enc)
# Set up tooltip encoding.
if x_column is not None and y_column is not None:
chart = chart.encode(
tooltip=_get_tooltip_encoding(
x_column,
y_column,
size_column,
color_column,
color_enc,
)
)
if (
chart_type is ChartType.LINE
and x_column is not None
# This is using the new selection API that was added in Altair 5.0.0
and is_altair_version_5_or_greater
):
return _add_improved_hover_tooltips(
chart, x_column, chart_width, chart_height, len(df)
).interactive(), add_rows_metadata
return chart.interactive(), add_rows_metadata
def _add_improved_hover_tooltips(
chart: alt.Chart,
x_column: str,
width: int | None,
height: int | None,
data_point_count: int,
) -> alt.LayerChart:
"""Adds improved hover tooltips to an existing line chart.
This implementation uses a three-layer approach for better performance:
1. Base chart layer: The original line chart
2. Detection layer: Invisible points for detecting the nearest point on hover
3. Highlight layer: Only renders the selected point(s) using transform_filter
The filter-based approach is more efficient than using conditional opacity
because it only renders the selected point(s) rather than evaluating opacity
for every single data point on each hover event.
"""
import altair as alt
# Throttle hover events for large datasets to 16ms (~60fps) to improve performance.
# For smaller datasets, use standard mousemove without throttling.
hover_event = (
"mousemove{16}"
if data_point_count > _LARGE_DATASET_POINT_THRESHOLD
else "mousemove"
)
# Create a selection that chooses the nearest point & selects based on x-value.
# Uses mouseleave instead of mouseout/pointerout for more reliable hover clearing
# (mouseout fires when moving over child elements like tooltips).
nearest = alt.selection_point(
nearest=True,
on=hover_event,
fields=[x_column],
empty=False,
clear="mouseleave",
)
# Detection layer: Invisible points for detecting the nearest point.
# This layer is needed because selections must be attached to a mark.
detection_points = chart.mark_point(opacity=0).add_params(nearest)
# Highlight layer: Only renders the selected point(s) using transform_filter.
# This is more efficient than conditional opacity because it only renders
# the filtered data (typically 1-2 points) rather than all points.
highlighted_points = chart.mark_point(filled=True, size=65).transform_filter(
nearest
)
layer_chart = (
alt.layer(chart, detection_points, highlighted_points)
.configure_legend(symbolType="stroke")
.properties(
width=width or 0,
height=height or 0,
)
)
return cast("alt.LayerChart", layer_chart)
def prep_chart_data_for_add_rows(
data: Data,
add_rows_metadata: AddRowsMetadata,
) -> tuple[Data, AddRowsMetadata]:
"""Prepares the data for add_rows on our built-in charts.
This includes aspects like conversion of the data to Pandas DataFrame,
changes to the index, and melting the data if needed.
"""
import pandas as pd
df = dataframe_util.convert_anything_to_pandas_df(data)
# Make range indices start at last_index.
if isinstance(df.index, pd.RangeIndex):
old_step = _get_pandas_index_attr(df, "step")
# We have to drop the predefined index
df = df.reset_index(drop=True)
old_stop = _get_pandas_index_attr(df, "stop")
if old_step is None or old_stop is None:
raise StreamlitAPIException("'RangeIndex' object has no attribute 'step'")
start = add_rows_metadata.last_index + old_step
stop = add_rows_metadata.last_index + old_step + old_stop
df.index = pd.RangeIndex(start=start, stop=stop, step=old_step)
add_rows_metadata.last_index = stop - 1
out_data, *_ = _prep_data(
df,
x_column=add_rows_metadata.columns["x_column"],
y_column_list=add_rows_metadata.columns["y_column_list"],
color_column=add_rows_metadata.columns["color_column"],
size_column=add_rows_metadata.columns["size_column"],
sort_column=add_rows_metadata.columns["sort_column"],
)
return out_data, add_rows_metadata
def _infer_vegalite_type(
data: pd.Series[Any],
) -> VegaLiteType:
"""
From an array-like input, infer the correct vega typecode
('ordinal', 'nominal', 'quantitative', or 'temporal').
Parameters
----------
data: Numpy array or Pandas Series
"""
# The code below is copied from Altair, and slightly modified.
# We copy this code here so we don't depend on private Altair functions.
# Source: https://github.com/altair-viz/altair/blob/62ca5e37776f5cecb27e83c1fbd5d685a173095d/altair/utils/core.py#L193
from pandas.api.types import infer_dtype
# STREAMLIT MOD: I'm using infer_dtype directly here, rather than using Altair's
# wrapper. Their wrapper is only there to support Pandas < 0.20, but Streamlit
# requires Pandas 1.3.
typ = infer_dtype(data)
if typ in [
"floating",
"mixed-integer-float",
"integer",
"mixed-integer",
"complex",
]:
return "quantitative"
if typ == "categorical" and data.cat.ordered:
# The original code returns a tuple here:
# return ("ordinal", data.cat.categories.tolist()) # noqa: ERA001
# But returning the tuple here isn't compatible with our
# built-in chart implementation. And it also doesn't seem to be necessary.
# Altair already extracts the correct sort order somewhere else.
# More info about the issue here: https://github.com/streamlit/streamlit/issues/7776
return "ordinal"
if typ in ["string", "bytes", "categorical", "boolean", "mixed", "unicode"]:
return "nominal"
if typ in [
"datetime",
"datetime64",
"timedelta",
"timedelta64",
"date",
"time",
"period",
]:
return "temporal"
# STREAMLIT MOD: I commented this out since Streamlit doesn't use warnings.warn.
# > warnings.warn(
# > "I don't know how to infer vegalite type from '{}'. "
# > "Defaulting to nominal.".format(typ),
# > stacklevel=1,
# > )
return "nominal"
def _get_pandas_index_attr(
data: pd.DataFrame | pd.Series[Any],
attr: str,
) -> Any | None:
return getattr(data.index, attr, None)
def _prep_data(
df: pd.DataFrame,
x_column: str | None,
y_column_list: list[str],
color_column: str | None,
size_column: str | None,
sort_column: str | None = None,
) -> tuple[pd.DataFrame, str | None, str | None, str | None, str | None, str | None]:
"""Prepares the data for charting. This is also used in add_rows.
Returns the prepared dataframe and the new names of the x column (taking the index
reset into consideration) and y, color, and size columns.
"""
# If y is provided, but x is not, we'll use the index as x.
# So we need to pull the index into its own column.
x_column = _maybe_reset_index_in_place(df, x_column, y_column_list)
# Drop columns we're not using.
selected_data = _drop_unused_columns(
df, x_column, color_column, size_column, sort_column, *y_column_list
)
# Maybe convert color to Vega colors.
_maybe_convert_color_column_in_place(selected_data, color_column)
# Make sure all columns have string names.
(
x_column,
y_column_list,
color_column,
size_column,
sort_column,
) = _convert_col_names_to_str_in_place(
selected_data, x_column, y_column_list, color_column, size_column, sort_column
)
# Maybe melt data from wide format into long format.
melted_data, y_column, color_column = _maybe_melt(
selected_data, x_column, y_column_list, color_column, size_column, sort_column
)
# Return the data, but also the new names to use for x, y, and color.
return melted_data, x_column, y_column, color_column, size_column, sort_column
def _last_index_for_melted_dataframes(
data: pd.DataFrame,
) -> Hashable | None:
return cast("Hashable", data.index[-1]) if data.index.size > 0 else None
def _is_date_column(df: pd.DataFrame, name: str | None) -> bool:
"""True if the column with the given name stores datetime.date values.
This function just checks the first value in the given column, so
it's meaningful only for columns whose values all share the same type.
Parameters
----------
df : pd.DataFrame
name : str
The column name
Returns
-------
bool
"""
if name is None:
return False
column = df[name]
if column.size == 0:
return False
return isinstance(column.iat[0], date)
def _melt_data(
df: pd.DataFrame,
columns_to_leave_alone: list[str],
columns_to_melt: list[str] | None,
new_y_column_name: str,
new_color_column_name: str,
) -> pd.DataFrame:
"""Converts a wide-format dataframe to a long-format dataframe.
You can find more info about melting on the Pandas documentation:
https://pandas.pydata.org/docs/reference/api/pandas.melt.html
Parameters
----------
df : pd.DataFrame
The dataframe to melt.
columns_to_leave_alone : list[str]
The columns to leave as they are.
columns_to_melt : list[str]
The columns to melt.
new_y_column_name : str
The name of the new column that will store the values of the melted columns.
new_color_column_name : str
The name of column that will store the original column names.
Returns
-------
pd.DataFrame
The melted dataframe.
Examples
--------
>>> import pandas as pd
>>> df = pd.DataFrame(
... {
... "a": [1, 2, 3],
... "b": [4, 5, 6],
... "c": [7, 8, 9],
... }
... )
>>> _melt_data(df, ["a"], ["b", "c"], "value", "color")
>>> a color value
>>> 0 1 b 4
>>> 1 2 b 5
>>> 2 3 b 6
>>> ...
"""
import pandas as pd
from pandas.api.types import infer_dtype
melted_df = pd.melt(
df,
id_vars=columns_to_leave_alone,
value_vars=columns_to_melt,
var_name=new_color_column_name,
value_name=new_y_column_name,
)
y_series = melted_df[new_y_column_name]
if (
y_series.dtype == "object"
and "mixed" in infer_dtype(y_series)
and len(y_series.unique()) > 100
):
raise StreamlitAPIException(
"The columns used for rendering the chart contain too many values with "
"mixed types. Please select the columns manually via the y parameter."
)
# Arrow has problems with object types after melting two different dtypes
# > pyarrow.lib.ArrowTypeError: "Expected a <TYPE> object, got a object"
return dataframe_util.fix_arrow_incompatible_column_types(
melted_df,
selected_columns=[
*columns_to_leave_alone,
new_color_column_name,
new_y_column_name,
],
)
def _maybe_reset_index_in_place(
df: pd.DataFrame, x_column: str | None, y_column_list: list[str]
) -> str | None:
if x_column is None and len(y_column_list) > 0:
if df.index.name is None:
# Pick column name that is unlikely to collide with user-given names.
x_column = _SEPARATED_INDEX_COLUMN_NAME
else:
# Reuse index's name for the new column.
x_column = str(df.index.name)
df.index.name = x_column
df.reset_index(inplace=True) # noqa: PD002
return x_column
def _drop_unused_columns(df: pd.DataFrame, *column_names: str | None) -> pd.DataFrame:
"""Returns a subset of df, selecting only column_names that aren't None."""
# We can't just call set(col_names) because sets don't have stable ordering,
# which means tests that depend on ordering will fail.
# Performance-wise, it's not a problem, though, since this function is only ever
# used on very small lists.
seen = set()
keep = []
for x in column_names:
if x is None:
continue
if x in seen:
continue
seen.add(x)
keep.append(x)
return df[keep] # ty: ignore[invalid-return-type]
def _maybe_convert_color_column_in_place(
df: pd.DataFrame, color_column: str | None
) -> None:
"""If needed, convert color column to a format Vega understands."""
if color_column is None or len(df[color_column]) == 0:
return
first_color_datum = df[color_column].iat[0]
if is_hex_color_like(first_color_datum):
# Hex is already CSS-valid.
pass
elif is_color_tuple_like(first_color_datum):
# Tuples need to be converted to CSS-valid.
df.loc[:, color_column] = df[color_column].apply(to_css_color)
else:
# Other kinds of colors columns (i.e. pure numbers or nominal strings) shouldn't
# be converted since they are treated by Vega-Lite as sequential or categorical
# colors.
pass
def _convert_col_names_to_str_in_place(
df: pd.DataFrame,
x_column: str | None,
y_column_list: list[str],
color_column: str | None,
size_column: str | None,
sort_column: str | None,
) -> tuple[str | None, list[str], str | None, str | None, str | None]:
"""Converts column names to strings, since Vega-Lite does not accept ints, etc."""
import pandas as pd
column_names = list(df.columns) # list() converts RangeIndex, etc, to regular list.
str_column_names = [str(c) for c in column_names]
df.columns = pd.Index(str_column_names)
return (
None if x_column is None else str(x_column),
[str(c) for c in y_column_list],
None if color_column is None else str(color_column),
None if size_column is None else str(size_column),
None if sort_column is None else str(sort_column),
)
def _parse_generic_column(
df: pd.DataFrame, column_or_value: Any
) -> tuple[str | None, Any]:
if isinstance(column_or_value, str) and column_or_value in df.columns:
column_name = column_or_value
value = None
else:
column_name = None
value = column_or_value
return column_name, value
def _parse_x_column(df: pd.DataFrame, x_from_user: str | None) -> str | None:
if x_from_user is None:
return None
if isinstance(x_from_user, str):
if x_from_user not in df.columns:
raise StreamlitColumnNotFoundError(df, x_from_user)
return x_from_user
raise StreamlitAPIException(
"x parameter should be a column name (str) or None to use the "
f" dataframe's index. Value given: {x_from_user} "
f"(type {type(x_from_user)})"
)
def _parse_sort_column(df: pd.DataFrame, sort_from_user: bool | str) -> str | None:
if sort_from_user is False or sort_from_user is True:
return None
sort_column = sort_from_user.removeprefix("-")
if sort_column not in df.columns:
raise StreamlitColumnNotFoundError(df, sort_column)
return sort_column
def _parse_y_columns(
df: pd.DataFrame,
y_from_user: str | Sequence[str] | None,
x_column: str | None,
) -> list[str]:
y_column_list: list[str] = []
if y_from_user is None:
y_column_list = list(df.columns)
elif isinstance(y_from_user, str):
y_column_list = [y_from_user]
else:
y_column_list = [
str(col) for col in dataframe_util.convert_anything_to_list(y_from_user)
]
for col in y_column_list:
if col not in df.columns:
raise StreamlitColumnNotFoundError(df, col)
# y_column_list should only include x_column when user explicitly asked for it.
if x_column in y_column_list and (not y_from_user or x_column not in y_from_user):
y_column_list.remove(x_column)
return y_column_list
def _get_offset_encoding(
chart_type: ChartType,
color_column: str | None,
) -> tuple[alt.XOffset, alt.YOffset]:
# Vega's Offset encoding channel is used to create grouped/non-stacked bar charts
import altair as alt
x_offset = alt.XOffset()
y_offset = alt.YOffset()
_color_column: str | alt.typing.Optional[Any] = (
color_column if color_column is not None else alt.Undefined
)
if chart_type is ChartType.VERTICAL_BAR:
x_offset = alt.XOffset(field=_color_column)
elif chart_type is ChartType.HORIZONTAL_BAR:
y_offset = alt.YOffset(field=_color_column)
return x_offset, y_offset
def _get_opacity_encoding(
chart_type: ChartType,
stack: bool | ChartStackType | None,
color_column: str | None,
) -> alt.OpacityValue | None:
import altair as alt
# Opacity set to 0.7 for all area charts
if color_column and chart_type == ChartType.AREA:
return alt.OpacityValue(0.7)
# Layered bar chart
if color_column and stack == "layered":
return alt.OpacityValue(0.7)
return None
def _get_axis_config(df: pd.DataFrame, column_name: str | None, grid: bool) -> alt.Axis:
import altair as alt
from pandas.api.types import is_integer_dtype
if column_name is not None and is_integer_dtype(df[column_name]):
# Use a max tick size of 1 for integer columns (prevents zoom into
# float numbers) and deactivate grid lines for x-axis
return alt.Axis(tickMinStep=1, grid=grid)
return alt.Axis(grid=grid)
def _maybe_melt(
df: pd.DataFrame,
x_column: str | None,
y_column_list: list[str],
color_column: str | None,
size_column: str | None,
sort_column: str | None,
) -> tuple[pd.DataFrame, str | None, str | None]:
"""If multiple columns are set for y, melt the dataframe into long format."""
y_column: str | None
if len(y_column_list) == 0:
y_column = None
elif len(y_column_list) == 1:
y_column = y_column_list[0]
elif x_column is not None:
# Pick column names that are unlikely to collide with user-given names.
y_column = _MELTED_Y_COLUMN_NAME
color_column = _MELTED_COLOR_COLUMN_NAME
columns_to_leave_alone = [x_column]
if size_column:
columns_to_leave_alone.append(size_column)
if sort_column:
columns_to_leave_alone.append(sort_column)
df = _melt_data(
df=df,
columns_to_leave_alone=columns_to_leave_alone,
columns_to_melt=y_column_list,
new_y_column_name=y_column,
new_color_column_name=color_column,
)
return df, y_column, color_column
def _get_axis_encodings(
df: pd.DataFrame,
chart_type: ChartType,
x_column: str | None,
y_column: str | None,
x_from_user: str | None,
y_from_user: str | Sequence[str] | None,
x_axis_label: str | None,
y_axis_label: str | None,
stack: bool | ChartStackType | None,
sort_from_user: bool | str,
) -> tuple[alt.X, alt.Y]:
stack_encoding: alt.X | alt.Y
sort_encoding: alt.X | alt.Y
if chart_type == ChartType.HORIZONTAL_BAR:
# Handle horizontal bar chart - switches x and y data:
x_encoding = _get_x_encoding(
df, y_column, y_from_user, x_axis_label, chart_type
)
y_encoding = _get_y_encoding(
df, x_column, x_from_user, y_axis_label, chart_type
)
stack_encoding = x_encoding
sort_encoding = y_encoding
else:
x_encoding = _get_x_encoding(
df, x_column, x_from_user, x_axis_label, chart_type
)
y_encoding = _get_y_encoding(
df, y_column, y_from_user, y_axis_label, chart_type
)
stack_encoding = y_encoding
sort_encoding = x_encoding
# Handle stacking - only relevant for bar & area charts
_update_encoding_with_stack(stack, stack_encoding)
# Handle sorting - only relevant for bar charts
if chart_type in (ChartType.VERTICAL_BAR, ChartType.HORIZONTAL_BAR):
_update_encoding_with_sort(sort_from_user, sort_encoding)
return x_encoding, y_encoding
def _get_x_encoding(
df: pd.DataFrame,
x_column: str | None,
x_from_user: str | Sequence[str] | None,
x_axis_label: str | None,
chart_type: ChartType,
) -> alt.X:
import altair as alt
if x_column is None:
# If no field is specified, the full axis disappears when no data is present.
# Maybe a bug in vega-lite? So we pass a field that doesn't exist.
x_field = _NON_EXISTENT_COLUMN_NAME
x_title = ""
elif x_column == _SEPARATED_INDEX_COLUMN_NAME:
# If the x column name is the crazy anti-collision name we gave it, then need to
# set up a title so we never show the crazy name to the user.
x_field = x_column
# Don't show a label in the x axis (not even a nice label like
# SEPARATED_INDEX_COLUMN_TITLE) when we pull the x axis from the index.
x_title = ""
else:
x_field = x_column
# Only show a label in the x axis if the user passed a column explicitly. We
# could go either way here, but I'm keeping this to avoid breaking the existing
# behavior.
x_title = "" if x_from_user is None else x_column
# User specified x-axis label takes precedence
if x_axis_label is not None:
x_title = x_axis_label
# grid lines on x axis for horizontal bar charts only
grid = chart_type == ChartType.HORIZONTAL_BAR
return alt.X(
x_field,
title=x_title,
type=_get_x_encoding_type(df, chart_type, x_column),
scale=alt.Scale(),
axis=_get_axis_config(df, x_column, grid=grid),
)
def _get_y_encoding(
df: pd.DataFrame,
y_column: str | None,
y_from_user: str | Sequence[str] | None,
y_axis_label: str | None,
chart_type: ChartType,
) -> alt.Y:
import altair as alt
if y_column is None:
# If no field is specified, the full axis disappears when no data is present.
# Maybe a bug in vega-lite? So we pass a field that doesn't exist.
y_field = _NON_EXISTENT_COLUMN_NAME
y_title = ""
elif y_column == _MELTED_Y_COLUMN_NAME:
# If the y column name is the crazy anti-collision name we gave it, then need to
# set up a title so we never show the crazy name to the user.
y_field = y_column
# Don't show a label in the y axis (not even a nice label like
# MELTED_Y_COLUMN_TITLE) when we pull the x axis from the index.
y_title = ""
else:
y_field = y_column
# Only show a label in the y axis if the user passed a column explicitly. We
# could go either way here, but I'm keeping this to avoid breaking the existing
# behavior.
y_title = "" if y_from_user is None else y_column
# User specified y-axis label takes precedence
if y_axis_label is not None:
y_title = y_axis_label
# grid lines on y axis for all charts except horizontal bar charts
grid = chart_type != ChartType.HORIZONTAL_BAR
return alt.Y(
field=y_field,
title=y_title,
type=_get_y_encoding_type(df, chart_type, y_column),
scale=alt.Scale(),
axis=_get_axis_config(df, y_column, grid=grid),
)
def _update_encoding_with_stack(
stack: bool | ChartStackType | None,
encoding: alt.X | alt.Y,
) -> None:
if stack is None:
return
# Our layered option maps to vega's stack=False option
if stack == "layered":
stack = False
encoding["stack"] = stack
def _update_encoding_with_sort(
sort_from_user: bool | str,
encoding: alt.X | alt.Y,
) -> None:
"""Apply sort to the given encoding in-place.
- If sort is False: disable Altair's default sorting on the bar's categorical axis
(i.e., set to None).
- If sort is True: use Altair's default sorting.
- If sort is a column name (optionally starting with '-') set a SortField with the correct order.
Note: Column validation should be done before calling this function.
"""
import altair as alt
if sort_from_user is False:
# Disable Altair's default sorting
encoding["sort"] = None
elif sort_from_user is True:
# Use Altair's default sorting
pass
else:
# String: sort by column name (optional '-' prefix for descending)
sort_order: Literal["ascending", "descending"]
if sort_from_user.startswith("-"):
sort_order = "descending"
else:
sort_order = "ascending"
sort_field = sort_from_user.removeprefix("-")
encoding["sort"] = alt.SortField(field=sort_field, order=sort_order)
def _get_color_encoding(
df: pd.DataFrame,
color_value: Color | None,
color_column: str | None,
y_column_list: list[str],
color_from_user: str | Color | list[Color] | None,
) -> alt.Color | alt.ColorValue | None:
import altair as alt
has_color_value = color_value not in [None, [], ()] # type: ignore[comparison-overlap]
# If user passed a color value, that should win over colors coming from the
# color column (be they manual or auto-assigned due to melting)
if has_color_value:
# If the color value is color-like, return that.
if is_color_like(cast("Any", color_value)):
if len(y_column_list) != 1:
raise StreamlitColorLengthError(
[color_value] if color_value else [], y_column_list
)
return alt.ColorValue(to_css_color(cast("Any", color_value)))
# If the color value is a list of colors of appropriate length, return that.
if isinstance(color_value, (list, tuple)):
color_values = cast("Collection[Color]", color_value)
if len(color_values) != len(y_column_list):
raise StreamlitColorLengthError(color_values, y_column_list)
if len(color_values) == 1:
return alt.ColorValue(to_css_color(cast("Any", color_value[0])))
return alt.Color(
field=color_column if color_column is not None else alt.Undefined,
scale=alt.Scale(
domain=y_column_list, range=[to_css_color(c) for c in color_values]
),
legend=_COLOR_LEGEND_SETTINGS,
type="nominal",
title=" ",
)
raise StreamlitInvalidColorError(color_from_user)
if color_column is not None:
column_type: VegaLiteType
column_type = (
"nominal"
if color_column == _MELTED_COLOR_COLUMN_NAME
else _infer_vegalite_type(df[color_column])
)
color_enc = alt.Color(
field=color_column, legend=_COLOR_LEGEND_SETTINGS, type=column_type
)
# Fix title if DF was melted
if color_column == _MELTED_COLOR_COLUMN_NAME:
# This has to contain an empty space, otherwise the
# full y-axis disappears (maybe a bug in vega-lite)?
color_enc["title"] = " "
# If the 0th element in the color column looks like a color, we'll use the color
# column's values as the colors in our chart.
elif len(df[color_column]) and is_color_like(df[color_column].iat[0]):
color_range = [to_css_color(c) for c in df[color_column].unique()]
color_enc["scale"] = alt.Scale(range=color_range)
# Don't show the color legend, because it will just show text with the
# color values, like #f00, #00f, etc, which are not user-readable.
color_enc["legend"] = None
# Otherwise, let Vega-Lite auto-assign colors.
# This codepath is typically reached when the color column contains numbers
# (in which case Vega-Lite uses a color gradient to represent them) or strings
# (in which case Vega-Lite assigns one color for each unique value).
else:
pass
return color_enc
return None
def _get_size_encoding(
chart_type: ChartType,
size_column: str | None,
size_value: str | float | None,
) -> alt.Size | alt.SizeValue | None:
import altair as alt
if chart_type == ChartType.SCATTER:
if size_column is not None:
return alt.Size(
size_column,
legend=_SIZE_LEGEND_SETTINGS,
)
if isinstance(size_value, (float, int)):
return alt.SizeValue(size_value)
if size_value is None:
return alt.SizeValue(100)
raise StreamlitAPIException(
f"This does not look like a valid size: {size_value!r}"
)
if size_column is not None or size_value is not None:
raise Error(
f"Chart type {chart_type.name} does not support size argument. "
"This should never happen!"
)
return None
def _get_tooltip_encoding(
x_column: str,
y_column: str,
size_column: str | None,
color_column: str | None,
color_enc: alt.Color | alt.ColorValue | None,
) -> list[alt.Tooltip]:
import altair as alt
tooltip = []
# If the x column name is the crazy anti-collision name we gave it, then need to set
# up a tooltip title so we never show the crazy name to the user.
if x_column == _SEPARATED_INDEX_COLUMN_NAME:
tooltip.append(alt.Tooltip(x_column, title=_SEPARATED_INDEX_COLUMN_TITLE))
else:
tooltip.append(alt.Tooltip(x_column))
# If the y column name is the crazy anti-collision name we gave it, then need to set
# up a tooltip title so we never show the crazy name to the user.
if y_column == _MELTED_Y_COLUMN_NAME:
tooltip.append(
alt.Tooltip(
y_column,
title=_MELTED_Y_COLUMN_TITLE,
# Just picked something random. Doesn't really matter:
type="quantitative",
)
)
else:
tooltip.append(alt.Tooltip(y_column))
# If we earlier decided that there should be no color legend, that's because the
# user passed a color column with actual color values (like "#ff0"), so we should
# not show the color values in the tooltip.
if color_column and getattr(color_enc, "legend", True) is not None:
# Use a human-readable title for the color.
if color_column == _MELTED_COLOR_COLUMN_NAME:
tooltip.append(
alt.Tooltip(
color_column,
title=_MELTED_COLOR_COLUMN_TITLE,
type="nominal",
)
)
else:
tooltip.append(alt.Tooltip(color_column))
if size_column:
tooltip.append(alt.Tooltip(size_column))
return tooltip
def _get_x_encoding_type(
df: pd.DataFrame, chart_type: ChartType, x_column: str | None
) -> VegaLiteType:
if x_column is None:
return "quantitative" # Anything. If None, Vega-Lite may hide the axis.
# Vertical bar charts should have a discrete (ordinal) x-axis,
# UNLESS type is date/time
# https://github.com/streamlit/streamlit/pull/2097#issuecomment-714802475
if chart_type == ChartType.VERTICAL_BAR and not _is_date_column(df, x_column):
return "ordinal"
return _infer_vegalite_type(df[x_column])
def _get_y_encoding_type(
df: pd.DataFrame, chart_type: ChartType, y_column: str | None
) -> VegaLiteType:
# Horizontal bar charts should have a discrete (ordinal) y-axis,
# UNLESS type is date/time
if chart_type == ChartType.HORIZONTAL_BAR and not _is_date_column(df, y_column):
return "ordinal"
if y_column:
return _infer_vegalite_type(df[y_column])
return "quantitative" # Pick anything. If undefined, Vega-Lite may hide the axis.
class StreamlitColumnNotFoundError(StreamlitAPIException):
def __init__(self, df: pd.DataFrame, col_name: str, *args: Any) -> None:
available_columns = ", ".join(str(c) for c in list(df.columns))
message = (
f'Data does not have a column named `"{col_name}"`. '
f"Available columns are `{available_columns}`"
)
super().__init__(message, *args)
class StreamlitInvalidColorError(StreamlitAPIException):
def __init__(self, color_from_user: str | Color | list[Color] | None) -> None:
message = f"""
This does not look like a valid color argument: `{color_from_user}`.
The color argument can be:
* A hex string like "#ffaa00" or "#ffaa0088".
* An RGB or RGBA tuple with the red, green, blue, and alpha
components specified as ints from 0 to 255 or floats from 0.0 to
1.0.
* The name of a column.
* Or a list of colors, matching the number of y columns to draw.
"""
super().__init__(message)
class StreamlitColorLengthError(StreamlitAPIException):
def __init__(
self,
color_values: str | Color | Collection[Color] | None,
y_column_list: list[str],
) -> None:
message = (
f"The list of colors `{color_values}` must have the same "
"length as the list of columns to be colored "
f"`{y_column_list}`."
)
super().__init__(message)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/lib/mutable_status_container.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import time
from typing import TYPE_CHECKING, Literal, TypeAlias, cast
from typing_extensions import Self
from streamlit.delta_generator import DeltaGenerator
from streamlit.elements.lib.layout_utils import (
WidthWithoutContent,
get_width_config,
validate_width,
)
from streamlit.errors import StreamlitAPIException
from streamlit.proto.Block_pb2 import Block as BlockProto
from streamlit.proto.ForwardMsg_pb2 import ForwardMsg
from streamlit.runtime.scriptrunner_utils.script_run_context import enqueue_message
if TYPE_CHECKING:
from types import TracebackType
from streamlit.cursor import Cursor
States: TypeAlias = Literal["running", "complete", "error"]
class StatusContainer(DeltaGenerator):
@staticmethod
def _create(
parent: DeltaGenerator,
label: str,
expanded: bool = False,
state: States = "running",
width: WidthWithoutContent = "stretch",
) -> StatusContainer:
expandable_proto = BlockProto.Expandable()
expandable_proto.expanded = expanded
expandable_proto.label = label or ""
if state == "running":
expandable_proto.icon = "spinner"
elif state == "complete":
expandable_proto.icon = ":material/check:"
elif state == "error":
expandable_proto.icon = ":material/error:"
else:
raise StreamlitAPIException(
f"Unknown state ({state}). Must be one of 'running', 'complete', or 'error'."
)
block_proto = BlockProto()
block_proto.allow_empty = True
block_proto.expandable.CopyFrom(expandable_proto)
validate_width(width=width)
block_proto.width_config.CopyFrom(get_width_config(width))
delta_path: list[int] = (
parent._active_dg._cursor.delta_path if parent._active_dg._cursor else []
)
status_container = cast(
"StatusContainer",
parent._block(block_proto=block_proto, dg_type=StatusContainer),
)
# Apply initial configuration
status_container._delta_path = delta_path
status_container._current_proto = block_proto
status_container._current_state = state
# We need to sleep here for a very short time to prevent issues when
# the status is updated too quickly. If an .update() directly follows the
# the initialization, sometimes only the latest update is applied.
# Adding a short timeout here allows the frontend to render the update before.
time.sleep(0.05)
return status_container
def __init__(
self,
root_container: int | None,
cursor: Cursor | None,
parent: DeltaGenerator | None,
block_type: str | None,
) -> None:
super().__init__(root_container, cursor, parent, block_type)
# Initialized in `_create()`:
self._current_proto: BlockProto | None = None
self._current_state: States | None = None
self._delta_path: list[int] | None = None
def update(
self,
*,
label: str | None = None,
expanded: bool | None = None,
state: States | None = None,
) -> None:
"""Update the status container.
Only specified arguments are updated. Container contents and unspecified
arguments remain unchanged.
Parameters
----------
label : str or None
A new label of the status container. If None, the label is not
changed.
expanded : bool or None
The new expanded state of the status container. If None,
the expanded state is not changed.
state : "running", "complete", "error", or None
The new state of the status container. This mainly changes the
icon. If None, the state is not changed.
"""
if self._current_proto is None or self._delta_path is None:
raise RuntimeError(
"StatusContainer is not correctly initialized. This should never happen."
)
msg = ForwardMsg()
msg.metadata.delta_path[:] = self._delta_path
msg.delta.add_block.CopyFrom(self._current_proto)
if expanded is not None:
msg.delta.add_block.expandable.expanded = expanded
else:
msg.delta.add_block.expandable.ClearField("expanded")
if label is not None:
msg.delta.add_block.expandable.label = label
if state is not None:
if state == "running":
msg.delta.add_block.expandable.icon = "spinner"
elif state == "complete":
msg.delta.add_block.expandable.icon = ":material/check:"
elif state == "error":
msg.delta.add_block.expandable.icon = ":material/error:"
else:
raise StreamlitAPIException(
f"Unknown state ({state}). Must be one of 'running', 'complete', or 'error'."
)
self._current_state = state
self._current_proto = msg.delta.add_block
enqueue_message(msg)
def __enter__(self) -> Self: # type: ignore[override]
# This is a little dubious: we're returning a different type than
# our superclass' `__enter__` function. Maybe DeltaGenerator.__enter__
# should always return `self`?
super().__enter__()
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> Literal[False]:
# Only update if the current state is running
if self._current_state == "running":
# We need to sleep here for a very short time to prevent issues when
# the status is updated too quickly. If an .update() is directly followed
# by the exit of the context manager, sometimes only the last update
# (to complete) is applied. Adding a short timeout here allows the frontend
# to render the update before.
time.sleep(0.05)
if exc_type is not None:
# If an exception was raised in the context,
# we want to update the status to error.
self.update(state="error")
else:
self.update(state="complete")
return super().__exit__(exc_type, exc_val, exc_tb)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/lib/color_util.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from collections.abc import Callable, Collection
from typing import Any, TypeAlias, cast
from streamlit.errors import StreamlitInvalidColorError
# components go from 0.0 to 1.0
# Supported by Pillow and pretty common.
FloatRGBColorTuple: TypeAlias = tuple[float, float, float]
FloatRGBAColorTuple: TypeAlias = tuple[float, float, float, float]
# components go from 0 to 255
# DeckGL uses these.
IntRGBColorTuple: TypeAlias = tuple[int, int, int]
IntRGBAColorTuple: TypeAlias = tuple[int, int, int, int]
# components go from 0 to 255, except alpha goes from 0.0 to 1.0
# CSS uses these.
MixedRGBAColorTuple: TypeAlias = tuple[int, int, int, float]
Color4Tuple: TypeAlias = FloatRGBAColorTuple | IntRGBAColorTuple | MixedRGBAColorTuple
Color3Tuple: TypeAlias = FloatRGBColorTuple | IntRGBColorTuple
ColorTuple: TypeAlias = Color4Tuple | Color3Tuple
IntColorTuple: TypeAlias = IntRGBColorTuple | IntRGBAColorTuple
ColorStr: TypeAlias = str
Color: TypeAlias = ColorTuple | ColorStr
MaybeColor: TypeAlias = str | Collection[Any]
def to_int_color_tuple(color: MaybeColor) -> IntColorTuple:
"""Convert input into color tuple of type (int, int, int, int)."""
color_tuple = _to_color_tuple(
color,
rgb_formatter=_int_formatter,
alpha_formatter=_int_formatter,
)
return cast("IntColorTuple", color_tuple)
def to_css_color(color: MaybeColor) -> Color:
"""Convert input into a CSS-compatible color that Vega can use.
Inputs must be a hex string, rgb()/rgba() string, or a color tuple. Inputs may not be a CSS
color name, other CSS color function (like "hsl(...)"), etc.
See tests for more info.
"""
if is_css_color_like(color):
return cast("Color", color)
if is_color_tuple_like(color):
ctuple = cast("ColorTuple", color)
ctuple = _normalize_tuple(ctuple, _int_formatter, _float_formatter)
if len(ctuple) == 3:
return f"rgb({ctuple[0]}, {ctuple[1]}, {ctuple[2]})"
if len(ctuple) == 4:
c4tuple = cast("MixedRGBAColorTuple", ctuple)
return f"rgba({c4tuple[0]}, {c4tuple[1]}, {c4tuple[2]}, {c4tuple[3]})"
raise StreamlitInvalidColorError(color)
def is_css_color_like(color: MaybeColor) -> bool:
"""Check whether the input looks like something Vega can use.
This is meant to be lightweight, and not a definitive answer. The definitive solution is to try
to convert and see if an error is thrown.
NOTE: We only accept hex colors and color tuples as user input. So do not use this function to
validate user input! Instead use is_hex_color_like and is_color_tuple_like.
"""
return is_hex_color_like(color) or _is_cssrgb_color_like(color)
def is_hex_color_like(color: MaybeColor) -> bool:
"""Check whether the input looks like a hex color.
This is meant to be lightweight, and not a definitive answer. The definitive solution is to try
to convert and see if an error is thrown.
"""
return (
isinstance(color, str)
and color.startswith("#")
and color[1:].isalnum() # Alphanumeric
and len(color) in {4, 5, 7, 9}
)
def _is_cssrgb_color_like(color: MaybeColor) -> bool:
"""Check whether the input looks like a CSS rgb() or rgba() color string.
This is meant to be lightweight, and not a definitive answer. The definitive solution is to try
to convert and see if an error is thrown.
NOTE: We only accept hex colors and color tuples as user input. So do not use this function to
validate user input! Instead use is_hex_color_like and is_color_tuple_like.
"""
return isinstance(color, str) and color.startswith(("rgb(", "rgba("))
def is_color_tuple_like(color: MaybeColor) -> bool:
"""Check whether the input looks like a tuple color.
This is meant to be lightweight, and not a definitive answer. The definitive solution is to try
to convert and see if an error is thrown.
"""
return (
isinstance(color, (tuple, list))
and len(color) in {3, 4}
and all(isinstance(c, (int, float)) for c in color)
)
def is_color_like(color: MaybeColor) -> bool:
"""A fairly lightweight check of whether the input is a color.
This isn't meant to be a definitive answer. The definitive solution is to
try to convert and see if an error is thrown.
"""
return is_css_color_like(color) or is_color_tuple_like(color)
# Wrote our own hex-to-tuple parser to avoid bringing in a dependency.
def _to_color_tuple(
color: MaybeColor,
rgb_formatter: Callable[[float, MaybeColor], float],
alpha_formatter: Callable[[float, MaybeColor], float],
) -> ColorTuple:
"""Convert a potential color to a color tuple.
The exact type of color tuple this outputs is dictated by the formatter parameters.
The R, G, B components are transformed by rgb_formatter, and the alpha component is transformed
by alpha_formatter.
For example, to output a (float, float, float, int) color tuple, set rgb_formatter
to _float_formatter and alpha_formatter to _int_formatter.
"""
if is_hex_color_like(color):
hex_len = len(color)
color_hex = cast("str", color)
if hex_len == 4:
r = 2 * color_hex[1]
g = 2 * color_hex[2]
b = 2 * color_hex[3]
a = "ff"
elif hex_len == 5:
r = 2 * color_hex[1]
g = 2 * color_hex[2]
b = 2 * color_hex[3]
a = 2 * color_hex[4]
elif hex_len == 7:
r = color_hex[1:3]
g = color_hex[3:5]
b = color_hex[5:7]
a = "ff"
elif hex_len == 9:
r = color_hex[1:3]
g = color_hex[3:5]
b = color_hex[5:7]
a = color_hex[7:9]
else:
raise StreamlitInvalidColorError(color)
try:
color = int(r, 16), int(g, 16), int(b, 16), int(a, 16)
except Exception as ex:
raise StreamlitInvalidColorError(color) from ex
if is_color_tuple_like(color):
color_tuple = cast("ColorTuple", color)
return _normalize_tuple(color_tuple, rgb_formatter, alpha_formatter)
raise StreamlitInvalidColorError(color)
def _normalize_tuple(
color: ColorTuple,
rgb_formatter: Callable[[float, MaybeColor], float],
alpha_formatter: Callable[[float, MaybeColor], float],
) -> ColorTuple:
"""Parse color tuple using the specified color formatters.
The R, G, B components are transformed by rgb_formatter, and the alpha component is transformed
by alpha_formatter.
For example, to output a (float, float, float, int) color tuple, set rgb_formatter
to _float_formatter and alpha_formatter to _int_formatter.
"""
if len(color) == 3:
r = rgb_formatter(color[0], color)
g = rgb_formatter(color[1], color)
b = rgb_formatter(color[2], color)
return r, g, b
if len(color) == 4:
color_4tuple = color
r = rgb_formatter(color_4tuple[0], color_4tuple)
g = rgb_formatter(color_4tuple[1], color_4tuple)
b = rgb_formatter(color_4tuple[2], color_4tuple)
alpha = alpha_formatter(color_4tuple[3], color_4tuple) # ty: ignore[index-out-of-bounds]
return r, g, b, alpha
raise StreamlitInvalidColorError(color)
def _int_formatter(component: float, color: MaybeColor) -> int:
"""Convert a color component (float or int) to an int from 0 to 255.
Anything too small will become 0, and anything too large will become 255.
"""
if isinstance(component, float):
component = int(component * 255)
if isinstance(component, int):
return min(255, max(component, 0))
raise StreamlitInvalidColorError(color)
def _float_formatter(component: float, color: MaybeColor) -> float:
"""Convert a color component (float or int) to a float from 0.0 to 1.0.
Anything too small will become 0.0, and anything too large will become 1.0.
"""
if isinstance(component, int):
component = component / 255.0
if isinstance(component, float):
return min(1.0, max(component, 0.0))
raise StreamlitInvalidColorError(color)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/lib/streamlit_plotly_theme.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import contextlib
from typing import Final
# This is the streamlit theme for plotly where we pass in a template.data
# and a template.layout.
# Template.data is for changing specific graph properties in a general aspect
# such as Contour plots or Waterfall plots.
# Template.layout is for changing things such as the x axis and fonts and other
# general layout properties for general graphs.
# We pass in temporary colors to the frontend and the frontend will replace
# those colors because we want to change colors based on the background color.
# Start at #0000001 because developers may be likely to use #000000
CATEGORY_0: Final = "#000001"
CATEGORY_1: Final = "#000002"
CATEGORY_2: Final = "#000003"
CATEGORY_3: Final = "#000004"
CATEGORY_4: Final = "#000005"
CATEGORY_5: Final = "#000006"
CATEGORY_6: Final = "#000007"
CATEGORY_7: Final = "#000008"
CATEGORY_8: Final = "#000009"
CATEGORY_9: Final = "#000010"
SEQUENTIAL_0: Final = "#000011"
SEQUENTIAL_1: Final = "#000012"
SEQUENTIAL_2: Final = "#000013"
SEQUENTIAL_3: Final = "#000014"
SEQUENTIAL_4: Final = "#000015"
SEQUENTIAL_5: Final = "#000016"
SEQUENTIAL_6: Final = "#000017"
SEQUENTIAL_7: Final = "#000018"
SEQUENTIAL_8: Final = "#000019"
SEQUENTIAL_9: Final = "#000020"
DIVERGING_0: Final = "#000021"
DIVERGING_1: Final = "#000022"
DIVERGING_2: Final = "#000023"
DIVERGING_3: Final = "#000024"
DIVERGING_4: Final = "#000025"
DIVERGING_5: Final = "#000026"
DIVERGING_6: Final = "#000027"
DIVERGING_7: Final = "#000028"
DIVERGING_8: Final = "#000029"
DIVERGING_9: Final = "#000030"
DIVERGING_10: Final = "#000031"
INCREASING: Final = "#000032"
DECREASING: Final = "#000033"
TOTAL: Final = "#000034"
GRAY_70: Final = "#000036"
GRAY_90: Final = "#000037"
BG_COLOR: Final = "#000038"
FADED_TEXT_05: Final = "#000039"
BG_MIX: Final = "#000040"
def configure_streamlit_plotly_theme() -> None:
"""Configure the Streamlit chart theme for Plotly.
The theme is only configured if Plotly is installed.
"""
# We do nothing if Plotly is not installed. This is expected since Plotly is an optional dependency.
with contextlib.suppress(ImportError):
import plotly.graph_objects as go
import plotly.io as pio
# Plotly represents continuous colorscale through an array of pairs.
# The pair's first index is the starting point and the next pair's first index is the end point.
# The pair's second index is the starting color and the next pair's second index is the end color.
# For more information, please refer to https://plotly.com/python/colorscales/
streamlit_colorscale = [
[0.0, SEQUENTIAL_0],
[0.1111111111111111, SEQUENTIAL_1],
[0.2222222222222222, SEQUENTIAL_2],
[0.3333333333333333, SEQUENTIAL_3],
[0.4444444444444444, SEQUENTIAL_4],
[0.5555555555555556, SEQUENTIAL_5],
[0.6666666666666666, SEQUENTIAL_6],
[0.7777777777777778, SEQUENTIAL_7],
[0.8888888888888888, SEQUENTIAL_8],
[1.0, SEQUENTIAL_9],
]
pio.templates["streamlit"] = go.layout.Template(
data=go.layout.template.Data(
candlestick=[
go.layout.template.data.Candlestick(
decreasing=go.candlestick.Decreasing(
line=go.candlestick.decreasing.Line(color=DECREASING)
),
increasing=go.candlestick.Increasing(
line=go.candlestick.increasing.Line(color=INCREASING)
),
)
],
contour=[
go.layout.template.data.Contour(colorscale=streamlit_colorscale)
],
contourcarpet=[
go.layout.template.data.Contourcarpet(
colorscale=streamlit_colorscale
)
],
heatmap=[
go.layout.template.data.Heatmap(colorscale=streamlit_colorscale)
],
histogram2d=[
go.layout.template.data.Histogram2d(colorscale=streamlit_colorscale)
],
icicle=[
go.layout.template.data.Icicle(
textfont=go.icicle.Textfont(color="white")
)
],
sankey=[
go.layout.template.data.Sankey(
textfont=go.sankey.Textfont(color=GRAY_70)
)
],
scatter=[
go.layout.template.data.Scatter(
marker=go.scatter.Marker(line=go.scatter.marker.Line(width=0))
)
],
table=[
go.layout.template.data.Table(
cells=go.table.Cells(
fill=go.table.cells.Fill(color=BG_COLOR),
font=go.table.cells.Font(color=GRAY_90),
line=go.table.cells.Line(color=FADED_TEXT_05),
),
header=go.table.Header(
font=go.table.header.Font(color=GRAY_70),
line=go.table.header.Line(color=FADED_TEXT_05),
fill=go.table.header.Fill(color=BG_MIX),
),
)
],
waterfall=[
go.layout.template.data.Waterfall(
increasing=go.waterfall.Increasing(
marker=go.waterfall.increasing.Marker(color=INCREASING)
),
decreasing=go.waterfall.Decreasing(
marker=go.waterfall.decreasing.Marker(color=DECREASING)
),
totals=go.waterfall.Totals(
marker=go.waterfall.totals.Marker(color=TOTAL)
),
connector=go.waterfall.Connector(
line=go.waterfall.connector.Line(color=GRAY_70, width=2)
),
)
],
),
layout=go.Layout(
colorway=[
CATEGORY_0,
CATEGORY_1,
CATEGORY_2,
CATEGORY_3,
CATEGORY_4,
CATEGORY_5,
CATEGORY_6,
CATEGORY_7,
CATEGORY_8,
CATEGORY_9,
],
colorscale=go.layout.Colorscale(
sequential=streamlit_colorscale,
sequentialminus=streamlit_colorscale,
diverging=[
[0.0, DIVERGING_0],
[0.1, DIVERGING_1],
[0.2, DIVERGING_2],
[0.3, DIVERGING_3],
[0.4, DIVERGING_4],
[0.5, DIVERGING_5],
[0.6, DIVERGING_6],
[0.7, DIVERGING_7],
[0.8, DIVERGING_8],
[0.9, DIVERGING_9],
[1.0, DIVERGING_10],
],
),
coloraxis=go.layout.Coloraxis(colorscale=streamlit_colorscale),
),
)
pio.templates.default = "streamlit"
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/lib/subtitle_utils.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import io
import os
import re
from pathlib import Path
from streamlit import runtime
from streamlit.runtime import caching
from streamlit.util import calc_md5
# Regular expression to match the SRT timestamp format
# It matches the
# "hours:minutes:seconds,milliseconds --> hours:minutes:seconds,milliseconds" format
SRT_VALIDATION_REGEX = r"\d{2}:\d{2}:\d{2},\d{3} --> \d{2}:\d{2}:\d{2},\d{3}"
SRT_CONVERSION_REGEX = r"(\d{2}:\d{2}:\d{2}),(\d{3})"
SUBTITLE_ALLOWED_FORMATS = (".srt", ".vtt")
def _is_srt(stream: str | io.BytesIO | bytes) -> bool:
# Handle raw bytes
if isinstance(stream, bytes):
stream = io.BytesIO(stream)
# Convert str to io.BytesIO if 'stream' is a string
if isinstance(stream, str):
stream = io.BytesIO(stream.encode("utf-8"))
# Set the stream position to the beginning in case it's been moved
stream.seek(0)
# Read enough bytes to reliably check for SRT patterns
# This might be adjusted, but 33 bytes should be enough to read the first numeric
# line, the full timestamp line, and a bit of the next line
header = stream.read(33)
try:
header_str = header.decode("utf-8").strip() # Decode and strip whitespace
except UnicodeDecodeError:
# If it's not valid utf-8, it's probably not a valid SRT file
return False
# Split the header into lines and process them
lines = header_str.split("\n")
# Check for the pattern of an SRT file: digit(s), newline, timestamp
if len(lines) >= 2 and lines[0].isdigit():
match = re.search(SRT_VALIDATION_REGEX, lines[1])
if match:
return True
return False
def _srt_to_vtt(srt_data: str | bytes) -> bytes:
"""
Convert subtitles from SubRip (.srt) format to WebVTT (.vtt) format.
This function accepts the content of the .srt file either as a string
or as a BytesIO stream.
Parameters
----------
srt_data : str or bytes
The content of the .srt file as a string or a bytes stream.
Returns
-------
bytes
The content converted into .vtt format.
"""
# If the input is a bytes stream, convert it to a string
if isinstance(srt_data, bytes):
# Decode the bytes to a UTF-8 string
try:
srt_data = srt_data.decode("utf-8")
except UnicodeDecodeError as e:
raise ValueError("Could not decode the input stream as UTF-8.") from e
if not isinstance(srt_data, str):
# If it's not a string by this point, something is wrong.
raise TypeError(
f"Input must be a string or a bytes stream, not {type(srt_data)}."
)
# Replace SubRip timing with WebVTT timing
vtt_data = re.sub(SRT_CONVERSION_REGEX, r"\1.\2", srt_data)
# Add WebVTT file header
vtt_content = "WEBVTT\n\n" + vtt_data
# Convert the vtt content to bytes
return vtt_content.strip().encode("utf-8")
def _handle_string_or_path_data(data_or_path: str | Path) -> bytes:
"""Handles string data, either as a file path or raw content."""
if os.path.isfile(data_or_path):
path = Path(data_or_path)
file_extension = path.suffix.lower()
if file_extension not in SUBTITLE_ALLOWED_FORMATS:
raise ValueError(
f"Incorrect subtitle format {file_extension}. Subtitles must be in "
f"one of the following formats: {', '.join(SUBTITLE_ALLOWED_FORMATS)}"
)
with open(data_or_path, "rb") as file:
content = file.read()
return _srt_to_vtt(content) if file_extension == ".srt" else content
if isinstance(data_or_path, Path):
raise ValueError(f"File {data_or_path} does not exist.") # noqa: TRY004
content_string = data_or_path.strip()
if content_string.startswith("WEBVTT") or content_string == "":
return content_string.encode("utf-8")
if _is_srt(content_string):
return _srt_to_vtt(content_string)
raise ValueError("The provided string neither matches valid VTT nor SRT format.")
def _handle_stream_data(stream: io.BytesIO) -> bytes:
"""Handles io.BytesIO data, converting SRT to VTT content if needed."""
stream.seek(0)
stream_data = stream.getvalue()
return _srt_to_vtt(stream_data) if _is_srt(stream) else stream_data
def _handle_bytes_data(data: bytes) -> bytes:
"""Handles io.BytesIO data, converting SRT to VTT content if needed."""
return _srt_to_vtt(data) if _is_srt(data) else data
def process_subtitle_data(
coordinates: str,
data: str | bytes | Path | io.BytesIO,
label: str,
) -> str:
# Determine the type of data and process accordingly
if isinstance(data, (str, Path)):
subtitle_data = _handle_string_or_path_data(data)
elif isinstance(data, io.BytesIO):
subtitle_data = _handle_stream_data(data)
elif isinstance(data, bytes):
subtitle_data = _handle_bytes_data(data)
else:
raise TypeError(f"Invalid binary data format for subtitle: {type(data)}.")
if runtime.exists():
filename = calc_md5(label.encode())
# Save the processed data and return the file URL
file_url = runtime.get_instance().media_file_mgr.add(
path_or_data=subtitle_data,
mimetype="text/vtt",
coordinates=coordinates,
file_name=f"{filename}.vtt",
)
caching.save_media_data(subtitle_data, "text/vtt", coordinates)
return file_url
# When running in "raw mode", we can't access the MediaFileManager.
return ""
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/lib/shortcut_utils.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from typing import (
Final,
)
from streamlit.errors import (
StreamlitAPIException,
)
_MODIFIER_ALIASES: Final[dict[str, str]] = {
"ctrl": "ctrl",
"control": "ctrl",
"cmd": "cmd",
"command": "cmd",
"meta": "cmd",
"alt": "alt",
"option": "alt",
"shift": "shift",
"mod": "ctrl",
}
_MODIFIER_ORDER: Final[tuple[str, ...]] = ("ctrl", "cmd", "alt", "shift")
_KEY_ALIASES: Final[dict[str, str]] = {
"enter": "enter",
"return": "enter",
"space": "space",
"spacebar": "space",
"tab": "tab",
"escape": "escape",
"esc": "escape",
"backspace": "backspace",
"delete": "delete",
"del": "delete",
"home": "home",
"end": "end",
"pageup": "pageup",
"pagedown": "pagedown",
"left": "left",
"arrowleft": "left",
"right": "right",
"arrowright": "right",
"up": "up",
"arrowup": "up",
"down": "down",
"arrowdown": "down",
}
_RESERVED_KEYS: Final[set[str]] = {"c", "r"}
def _normalize_key_token(lower_token: str) -> str:
"""Normalize a key token to a format that can be used on the client side."""
if lower_token in _KEY_ALIASES:
return _KEY_ALIASES[lower_token]
if len(lower_token) == 1 and lower_token.isalnum():
return lower_token
if lower_token.startswith("f") and lower_token[1:].isdigit():
return lower_token
raise StreamlitAPIException(
"shortcut must include a single character or one of the supported keys "
"(e.g. Enter, Space, Tab, Escape)."
)
def normalize_shortcut(shortcut: str) -> str:
"""Normalize a shortcut string to a format that can be used on the client side.
Parameters
----------
shortcut : str
The shortcut string to normalize.
Returns
-------
str
The normalized shortcut string.
Raises
------
StreamlitAPIException
If the shortcut is not a string value.
If the shortcut does not contain at least one key or modifier.
If the shortcut contains a single non-modifier key.
If the shortcut uses the keys 'C' or 'R', with or without modifiers.
If the shortcut does not include a non-modifier key.
"""
if not isinstance(shortcut, str):
raise StreamlitAPIException("shortcut must be a string value.")
tokens = [token.strip() for token in shortcut.split("+") if token.strip()]
if not tokens:
raise StreamlitAPIException(
"The `shortcut` must contain at least one key or modifier."
)
modifiers: list[str] = []
key: str | None = None
for raw_token in tokens:
lower_token = raw_token.lower()
if lower_token in _MODIFIER_ALIASES:
normalized_modifier = _MODIFIER_ALIASES[lower_token]
if normalized_modifier not in modifiers:
modifiers.append(normalized_modifier)
continue
if key is not None:
raise StreamlitAPIException(
"The `shortcut` may only specify a single non-modifier key."
)
normalized_key = _normalize_key_token(lower_token)
if normalized_key in _RESERVED_KEYS:
raise StreamlitAPIException(
"The `shortcut` cannot use the keys 'C' or 'R', with or without modifiers."
)
key = normalized_key
if key is None:
raise StreamlitAPIException(
"The `shortcut` must include a non-modifier key such as 'K' or 'Ctrl+K'."
)
normalized_tokens: list[str] = [
modifier for modifier in _MODIFIER_ORDER if modifier in modifiers
]
if key is not None:
normalized_tokens.append(key)
return "+".join(normalized_tokens)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/lib/form_utils.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from typing import TYPE_CHECKING, NamedTuple
from streamlit import runtime
from streamlit.delta_generator_singletons import context_dg_stack
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
class FormData(NamedTuple):
"""Form data stored on a DeltaGenerator."""
# The form's unique ID.
form_id: str
def _current_form(this_dg: DeltaGenerator) -> FormData | None:
"""Find the FormData for the given DeltaGenerator.
Forms are blocks, and can have other blocks nested inside them.
To find the current form, we walk up the dg_stack until we find
a DeltaGenerator that has FormData.
"""
if not runtime.exists():
return None
if this_dg._form_data is not None:
return this_dg._form_data
if this_dg == this_dg._main_dg:
# We were created via an `st.foo` call.
# Walk up the dg_stack to see if we're nested inside a `with st.form` statement.
for dg in reversed(context_dg_stack.get()):
if dg._form_data is not None:
return dg._form_data
else:
# We were created via an `dg.foo` call.
# Take a look at our parent's form data to see if we're nested inside a form.
parent = this_dg._parent
if parent is not None and parent._form_data is not None:
return parent._form_data
return None
def current_form_id(dg: DeltaGenerator) -> str:
"""Return the form_id for the current form, or the empty string if we're
not inside an `st.form` block.
(We return the empty string, instead of None, because this value is
assigned to protobuf message fields, and None is not valid.)
"""
form_data = _current_form(dg)
if form_data is None:
return ""
return form_data.form_id
def is_in_form(dg: DeltaGenerator) -> bool:
"""True if the DeltaGenerator is inside an st.form block."""
return current_form_id(dg) != ""
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/lib/options_selector_utils.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from enum import Enum, EnumMeta
from typing import TYPE_CHECKING, Any, Final, TypeVar, overload
from streamlit import config, logger
from streamlit.dataframe_util import OptionSequence, convert_anything_to_list
from streamlit.errors import StreamlitAPIException
from streamlit.runtime.state.common import RegisterWidgetResult
from streamlit.type_util import (
check_python_comparable,
)
if TYPE_CHECKING:
from collections.abc import Callable, Iterable, Sequence
_LOGGER: Final = logger.get_logger(__name__)
_FLOAT_EQUALITY_EPSILON: Final[float] = 0.000000000005
_Value = TypeVar("_Value")
T = TypeVar("T")
def index_(iterable: Iterable[_Value], x: _Value) -> int:
"""Return zero-based index of the first item whose value is equal to x.
Raises a ValueError if there is no such item.
We need a custom implementation instead of the built-in list .index() to
be compatible with NumPy array and Pandas Series.
Parameters
----------
iterable : list, tuple, numpy.ndarray, pandas.Series
x : Any
Returns
-------
int
"""
for i, value in enumerate(iterable):
if x == value:
return i
if (
isinstance(value, float)
and isinstance(x, float)
and abs(x - value) < _FLOAT_EQUALITY_EPSILON
):
return i
raise ValueError(f"{x} is not in iterable")
def check_and_convert_to_indices(
opt: Sequence[Any], default_values: Sequence[Any] | Any | None
) -> list[int] | None:
"""Perform validation checks and return indices based on the default values."""
if default_values is None:
return None
default_values = convert_anything_to_list(default_values)
for value in default_values:
if value not in opt:
raise StreamlitAPIException(
f"The default value '{value}' is not part of the options. "
"Please make sure that every default values also exists in the options."
)
return [opt.index(value) for value in default_values]
def convert_to_sequence_and_check_comparable(options: OptionSequence[T]) -> Sequence[T]:
indexable_options = convert_anything_to_list(options)
check_python_comparable(indexable_options)
return indexable_options
def get_default_indices(
indexable_options: Sequence[T], default: Sequence[Any] | Any | None = None
) -> list[int]:
default_indices = check_and_convert_to_indices(indexable_options, default)
return default_indices if default_indices is not None else []
E1 = TypeVar("E1", bound=Enum)
E2 = TypeVar("E2", bound=Enum)
_ALLOWED_ENUM_COERCION_CONFIG_SETTINGS = ("off", "nameOnly", "nameAndValue")
def _coerce_enum(from_enum_value: E1, to_enum_class: type[E2]) -> E1 | E2:
"""Attempt to coerce an Enum value to another EnumMeta.
An Enum value of EnumMeta E1 is considered coercible to EnumType E2
if the EnumMeta __qualname__ match and the names of their members
match as well. (This is configurable in streamlist configs)
"""
if not isinstance(from_enum_value, Enum):
raise ValueError( # noqa: TRY004
f"Expected an Enum in the first argument. Got {type(from_enum_value)}"
)
if not isinstance(to_enum_class, EnumMeta):
raise ValueError( # noqa: TRY004
f"Expected an EnumMeta/Type in the second argument. Got {type(to_enum_class)}"
)
if isinstance(from_enum_value, to_enum_class):
return from_enum_value # Enum is already a member, no coersion necessary
coercion_type = config.get_option("runner.enumCoercion")
if coercion_type not in _ALLOWED_ENUM_COERCION_CONFIG_SETTINGS:
raise StreamlitAPIException(
"Invalid value for config option runner.enumCoercion. "
f"Expected one of {_ALLOWED_ENUM_COERCION_CONFIG_SETTINGS}, "
f"but got '{coercion_type}'."
)
if coercion_type == "off":
return from_enum_value # do not attempt to coerce
# We now know this is an Enum AND the user has configured coercion enabled.
# Check if we do NOT meet the required conditions and log a failure message
# if that is the case.
from_enum_class = from_enum_value.__class__
if (
from_enum_class.__qualname__ != to_enum_class.__qualname__
or (
coercion_type == "nameOnly"
and set(to_enum_class._member_names_) != set(from_enum_class._member_names_)
)
or (
coercion_type == "nameAndValue"
and set(to_enum_class._value2member_map_)
!= set(from_enum_class._value2member_map_)
)
):
_LOGGER.debug("Failed to coerce %s to class %s", from_enum_value, to_enum_class)
return from_enum_value # do not attempt to coerce
# At this point we think the Enum is coercible, and we know
# E1 and E2 have the same member names. We convert from E1 to E2 using _name_
# (since user Enum subclasses can override the .name property in 3.11)
_LOGGER.debug("Coerced %s to class %s", from_enum_value, to_enum_class)
return to_enum_class[from_enum_value._name_]
def _extract_common_class_from_iter(iterable: Iterable[Any]) -> Any:
"""Return the common class of all elements in a iterable if they share one.
Otherwise, return None.
"""
try:
inner_iter = iter(iterable)
first_class = type(next(inner_iter))
except StopIteration:
return None
if all(type(item) is first_class for item in inner_iter):
return first_class
return None
@overload
def maybe_coerce_enum(
register_widget_result: RegisterWidgetResult[Enum],
options: type[Enum],
opt_sequence: Sequence[Any],
) -> RegisterWidgetResult[Enum]: ...
@overload
def maybe_coerce_enum(
register_widget_result: RegisterWidgetResult[T],
options: OptionSequence[T],
opt_sequence: Sequence[T],
) -> RegisterWidgetResult[T]: ...
def maybe_coerce_enum(
register_widget_result: RegisterWidgetResult[Any],
options: OptionSequence[Any],
opt_sequence: Sequence[Any],
) -> RegisterWidgetResult[Any]:
"""Maybe Coerce a RegisterWidgetResult with an Enum member value to
RegisterWidgetResult[option] if option is an EnumType, otherwise just return
the original RegisterWidgetResult.
"""
# If the value is not a Enum, return early
if not isinstance(register_widget_result.value, Enum):
return register_widget_result
coerce_class: EnumMeta | None
if isinstance(options, EnumMeta):
coerce_class = options
else:
coerce_class = _extract_common_class_from_iter(opt_sequence)
if coerce_class is None:
return register_widget_result
return RegisterWidgetResult(
_coerce_enum(register_widget_result.value, coerce_class),
register_widget_result.value_changed,
)
# slightly ugly typing because TypeVars with Generic Bounds are not supported
# (https://github.com/python/typing/issues/548)
@overload
def maybe_coerce_enum_sequence(
register_widget_result: RegisterWidgetResult[list[T] | list[T | str]],
options: OptionSequence[T],
opt_sequence: Sequence[T],
) -> RegisterWidgetResult[list[T] | list[T | str]]: ...
@overload
def maybe_coerce_enum_sequence(
register_widget_result: RegisterWidgetResult[tuple[T, T]],
options: OptionSequence[T],
opt_sequence: Sequence[T],
) -> RegisterWidgetResult[tuple[T, T]]: ...
def maybe_coerce_enum_sequence(
register_widget_result: RegisterWidgetResult[list[Any] | tuple[Any, ...]],
options: OptionSequence[Any],
opt_sequence: Sequence[Any],
) -> RegisterWidgetResult[list[Any] | tuple[Any, ...]]:
"""Maybe Coerce a RegisterWidgetResult with a sequence of Enum members as value
to RegisterWidgetResult[Sequence[option]] if option is an EnumType, otherwise just
return the original RegisterWidgetResult.
"""
# If not all widget values are Enums, return early
if not all(isinstance(val, Enum) for val in register_widget_result.value):
return register_widget_result
# Extract the class to coerce
coerce_class: EnumMeta | None
if isinstance(options, EnumMeta):
coerce_class = options
else:
coerce_class = _extract_common_class_from_iter(opt_sequence)
if coerce_class is None:
return register_widget_result
# Return a new RegisterWidgetResult with the coerced enum values sequence
return RegisterWidgetResult(
type(register_widget_result.value)(
_coerce_enum(val, coerce_class) for val in register_widget_result.value
),
register_widget_result.value_changed,
)
def create_mappings(
options: Sequence[T], format_func: Callable[[T], str] = str
) -> tuple[list[str], dict[str, int]]:
"""Iterates through the options and formats them using the format_func.
Returns a tuple of the formatted options and a mapping of the formatted options to
the original options.
"""
formatted_option_to_option_mapping: dict[str, int] = {}
formatted_options: list[str] = []
for index, option in enumerate(options):
formatted_option = format_func(option)
formatted_options.append(formatted_option)
formatted_option_to_option_mapping[formatted_option] = index
return (
formatted_options,
formatted_option_to_option_mapping,
)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/lib/dicttools.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
"""Tools for working with dicts."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from collections.abc import Mapping
def _unflatten_single_dict(flat_dict: dict[Any, Any]) -> dict[Any, Any]:
"""Convert a flat dict of key-value pairs to dict tree.
Example
-------
_unflatten_single_dict({
foo_bar_baz: 123,
foo_bar_biz: 456,
x_bonks: 'hi',
})
# Returns:
# {
# foo: {
# bar: {
# baz: 123,
# biz: 456,
# },
# },
# x: {
# bonks: 'hi'
# }
# }
Parameters
----------
flat_dict : dict
A one-level dict where keys are fully-qualified paths separated by
underscores.
Returns
-------
dict
A tree made of dicts inside of dicts.
"""
out: dict[str, Any] = {}
for pathstr, v in flat_dict.items():
path = pathstr.split("_")
prev_dict: dict[str, Any] | None = None
curr_dict = out
for k in path:
if k not in curr_dict:
curr_dict[k] = {}
prev_dict = curr_dict
curr_dict = curr_dict[k]
if prev_dict is not None:
prev_dict[k] = v
return out
def unflatten(
flat_dict: dict[Any, Any], encodings: set[str] | None = None
) -> dict[Any, Any]:
"""Converts a flat dict of key-value pairs to a spec tree.
Example
-------
unflatten({
foo_bar_baz: 123,
foo_bar_biz: 456,
x_bonks: 'hi',
}, ['x'])
# Returns:
# {
# foo: {
# bar: {
# baz: 123,
# biz: 456,
# },
# },
# encoding: { # This gets added automatically
# x: {
# bonks: 'hi'
# }
# }
# }
Args
----
flat_dict: dict
A flat dict where keys are fully-qualified paths separated by
underscores.
encodings: set
Key names that should be automatically moved into the 'encoding' key.
Returns
-------
A tree made of dicts inside of dicts.
"""
if encodings is None:
encodings = set()
out_dict = _unflatten_single_dict(flat_dict)
for k, v in list(out_dict.items()):
# Unflatten child dicts:
if isinstance(v, dict):
v = unflatten(v, encodings) # noqa: PLW2901
elif hasattr(v, "__iter__"):
for i, child in enumerate(v):
if isinstance(child, dict):
v[i] = unflatten(child, encodings)
# Move items into 'encoding' if needed:
if k in encodings:
if "encoding" not in out_dict:
out_dict["encoding"] = {}
out_dict["encoding"][k] = v
out_dict.pop(k)
return out_dict
def remove_none_values(input_dict: Mapping[Any, Any]) -> dict[Any, Any]:
"""Remove all keys with None values from a dict."""
new_dict = {}
for key, val in input_dict.items():
if val is not None:
new_dict[key] = remove_none_values(val) if isinstance(val, dict) else val
return new_dict
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/lib/dialog.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from typing import TYPE_CHECKING, Literal, TypeAlias, cast
from typing_extensions import Self
from streamlit.delta_generator import DeltaGenerator
from streamlit.elements.lib.utils import compute_and_register_element_id
from streamlit.errors import StreamlitAPIException
from streamlit.proto.Block_pb2 import Block as BlockProto
from streamlit.proto.ForwardMsg_pb2 import ForwardMsg
from streamlit.runtime.scriptrunner_utils.script_run_context import (
enqueue_message,
get_script_run_ctx,
)
from streamlit.runtime.state import register_widget
if TYPE_CHECKING:
from types import TracebackType
from streamlit.cursor import Cursor
from streamlit.runtime.state import WidgetCallback
DialogWidth: TypeAlias = Literal["small", "large", "medium"]
def _process_dialog_width_input(
width: DialogWidth,
) -> BlockProto.Dialog.DialogWidth.ValueType:
"""Maps the user-provided literal to a value of the DialogWidth proto enum.
Returns the mapped enum field for "small" by default and otherwise the mapped type.
"""
if width == "large":
return BlockProto.Dialog.DialogWidth.LARGE
if width == "medium":
return BlockProto.Dialog.DialogWidth.MEDIUM
return BlockProto.Dialog.DialogWidth.SMALL
def _assert_first_dialog_to_be_opened(should_open: bool) -> None:
"""Check whether a dialog has already been opened in the same script run.
Only one dialog is supposed to be opened. The check is implemented in a way
that for a script run, the open function can only be called once.
One dialog at a time is a product decision and not a technical one.
Raises
------
StreamlitAPIException
Raised when a dialog has already been opened in the current script run.
"""
script_run_ctx = get_script_run_ctx()
# We don't reset the ctx.has_dialog_opened when the flag is False because
# it is reset in a new scriptrun anyways. If the execution model ever changes,
# this might need to change.
if should_open and script_run_ctx:
if script_run_ctx.has_dialog_opened:
raise StreamlitAPIException(
"Only one dialog is allowed to be opened at the same time. "
"Please make sure to not call a dialog-decorated function more than once in a script run."
)
script_run_ctx.has_dialog_opened = True
class Dialog(DeltaGenerator):
@staticmethod
def _create(
parent: DeltaGenerator,
title: str,
*,
dismissible: bool = True,
width: DialogWidth = "small",
on_dismiss: Literal["ignore", "rerun"] | WidgetCallback = "ignore",
) -> Dialog:
# Validation for on_dismiss parameter
if on_dismiss not in ["ignore", "rerun"] and not callable(on_dismiss):
raise StreamlitAPIException(
f"You have passed {on_dismiss} to `on_dismiss`. But only 'ignore', "
"'rerun', or a callable is supported."
)
block_proto = BlockProto()
block_proto.dialog.title = title
block_proto.dialog.dismissible = dismissible
block_proto.dialog.width = _process_dialog_width_input(width)
# Handle on_dismiss functionality
is_dismiss_activated = on_dismiss != "ignore"
element_id = None
if is_dismiss_activated:
# Register as widget when on_dismiss is activated
ctx = get_script_run_ctx()
element_id = compute_and_register_element_id(
"dialog",
user_key=None,
key_as_main_identity=False,
dg=parent,
title=title,
dismissible=dismissible,
width=width,
on_dismiss=str(on_dismiss) if not callable(on_dismiss) else "callback",
)
block_proto.dialog.id = element_id
register_widget(
element_id,
on_change_handler=on_dismiss if callable(on_dismiss) else None,
deserializer=lambda x: x, # Simple passthrough for trigger values
serializer=lambda x: x, # Simple passthrough for trigger values
ctx=ctx,
value_type="trigger_value",
)
# We store the delta path here, because in _update we enqueue a new proto
# message to update the open status. Without this, the dialog content is gone
# when the _update message is sent
delta_path: list[int] = (
parent._active_dg._cursor.delta_path if parent._active_dg._cursor else []
)
dialog = cast("Dialog", parent._block(block_proto=block_proto, dg_type=Dialog))
dialog._delta_path = delta_path
dialog._current_proto = block_proto
return dialog
def __init__(
self,
root_container: int | None,
cursor: Cursor | None,
parent: DeltaGenerator | None,
block_type: str | None,
) -> None:
super().__init__(root_container, cursor, parent, block_type)
# Initialized in `_create()`:
self._current_proto: BlockProto | None = None
self._delta_path: list[int] | None = None
def _update(self, should_open: bool) -> None:
"""Send an updated proto message to indicate the open-status for the dialog."""
if self._current_proto is None or self._delta_path is None:
raise RuntimeError(
"Dialog not correctly initialized. This should never happen."
)
_assert_first_dialog_to_be_opened(should_open)
msg = ForwardMsg()
msg.metadata.delta_path[:] = self._delta_path
msg.delta.add_block.CopyFrom(self._current_proto)
msg.delta.add_block.dialog.is_open = should_open
self._current_proto = msg.delta.add_block
enqueue_message(msg)
def open(self) -> None:
self._update(True)
def close(self) -> None:
self._update(False)
def __enter__(self) -> Self: # type: ignore[override]
# This is a little dubious: we're returning a different type than
# our superclass' `__enter__` function. Maybe DeltaGenerator.__enter__
# should always return `self`?
super().__enter__()
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> Literal[False]:
return super().__exit__(exc_type, exc_val, exc_tb)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/lib/column_types.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
# Allow function names with uppercase letters:
# ruff: noqa: N802
from __future__ import annotations
import datetime
import itertools
from typing import TYPE_CHECKING, Literal, TypeAlias, TypedDict
from typing_extensions import NotRequired
from streamlit.elements.lib.color_util import is_css_color_like
from streamlit.errors import StreamlitValueError
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.string_util import validate_material_icon
if TYPE_CHECKING:
from collections.abc import Callable, Iterable, Iterator
NumberFormat: TypeAlias = Literal[
"plain",
"localized",
"dollar",
"euro",
"yen",
"percent",
"compact",
"scientific",
"engineering",
"accounting",
"bytes",
]
ColumnWidth: TypeAlias = Literal["small", "medium", "large"] | int
# Type alias that represents all available column types
# which are configurable by the user.
ColumnType: TypeAlias = Literal[
"object",
"text",
"number",
"checkbox",
"selectbox",
"list",
"datetime",
"date",
"time",
"link",
"line_chart",
"bar_chart",
"area_chart",
"image",
"progress",
"multiselect",
"json",
]
# Themeable colors supported in the theme config:
ThemeColor: TypeAlias = Literal[
"red",
"blue",
"green",
"yellow",
"orange",
"violet",
"gray",
"grey",
"primary",
]
# Color options for chart columns:
ChartColor: TypeAlias = Literal["auto", "auto-inverse"] | ThemeColor | str
def _validate_chart_color(maybe_color: str) -> None:
"""Validate a color for a chart column."""
supported_colors = [
"auto",
"auto-inverse",
"red",
"blue",
"green",
"yellow",
"violet",
"orange",
"gray",
"grey",
"primary",
]
if maybe_color not in supported_colors and not is_css_color_like(maybe_color):
raise StreamlitValueError(
"color",
[
*supported_colors,
"a valid hex color",
"an rgb() or rgba() color",
],
)
class NumberColumnConfig(TypedDict):
type: Literal["number"]
format: NotRequired[str | NumberFormat | None]
min_value: NotRequired[int | float | None]
max_value: NotRequired[int | float | None]
step: NotRequired[int | float | None]
class TextColumnConfig(TypedDict):
type: Literal["text"]
max_chars: NotRequired[int | None]
validate: NotRequired[str | None]
class CheckboxColumnConfig(TypedDict):
type: Literal["checkbox"]
SelectboxOptionValue: TypeAlias = str | int | float | bool
class SelectboxOption(TypedDict):
value: SelectboxOptionValue
label: NotRequired[str | None]
class SelectboxColumnConfig(TypedDict):
type: Literal["selectbox"]
options: NotRequired[list[SelectboxOptionValue | SelectboxOption] | None]
class LinkColumnConfig(TypedDict):
type: Literal["link"]
max_chars: NotRequired[int | None]
validate: NotRequired[str | None]
display_text: NotRequired[str | None]
class BarChartColumnConfig(TypedDict):
type: Literal["bar_chart"]
y_min: NotRequired[int | float | None]
y_max: NotRequired[int | float | None]
color: NotRequired[ChartColor | None]
class LineChartColumnConfig(TypedDict):
type: Literal["line_chart"]
y_min: NotRequired[int | float | None]
y_max: NotRequired[int | float | None]
color: NotRequired[ChartColor | None]
class AreaChartColumnConfig(TypedDict):
type: Literal["area_chart"]
y_min: NotRequired[int | float | None]
y_max: NotRequired[int | float | None]
color: NotRequired[ChartColor | None]
class ImageColumnConfig(TypedDict):
type: Literal["image"]
class ListColumnConfig(TypedDict):
type: Literal["list"]
class MultiselectOption(TypedDict):
value: str
label: NotRequired[str | None]
color: NotRequired[str | Literal["auto"] | ThemeColor | None]
class MultiselectColumnConfig(TypedDict):
type: Literal["multiselect"]
options: NotRequired[Iterable[MultiselectOption | str] | None]
accept_new_options: NotRequired[bool | None]
class DatetimeColumnConfig(TypedDict):
type: Literal["datetime"]
format: NotRequired[
str | Literal["localized", "distance", "calendar", "iso8601"] | None
]
min_value: NotRequired[str | None]
max_value: NotRequired[str | None]
step: NotRequired[int | float | None]
timezone: NotRequired[str | None]
class TimeColumnConfig(TypedDict):
type: Literal["time"]
format: NotRequired[str | Literal["localized", "iso8601"] | None]
min_value: NotRequired[str | None]
max_value: NotRequired[str | None]
step: NotRequired[int | float | None]
class DateColumnConfig(TypedDict):
type: Literal["date"]
format: NotRequired[str | Literal["localized", "distance", "iso8601"] | None]
min_value: NotRequired[str | None]
max_value: NotRequired[str | None]
step: NotRequired[int | None]
class ProgressColumnConfig(TypedDict):
type: Literal["progress"]
format: NotRequired[str | NumberFormat | None]
min_value: NotRequired[int | float | None]
max_value: NotRequired[int | float | None]
step: NotRequired[int | float | None]
color: NotRequired[ChartColor | None]
class JsonColumnConfig(TypedDict):
type: Literal["json"]
class ColumnConfig(TypedDict, total=False):
"""Configuration options for columns in ``st.dataframe`` and ``st.data_editor``.
Parameters
----------
label : str or None
The label shown at the top of the column. If this is ``None``
(default), the column name is used.
width : "small", "medium", "large", int, or None
The display width of the column. If this is ``None`` (default), the
column will be sized to fit the cell contents. Otherwise, this can be
one of the following:
- ``"small"``: 75px wide
- ``"medium"``: 200px wide
- ``"large"``: 400px wide
- An integer specifying the width in pixels
If the total width of all columns is less than the width of the
dataframe, the remaining space will be distributed evenly among all
columns.
help : str or None
A tooltip that gets displayed when hovering over the column label. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown, including
the Markdown directives described in the ``body`` parameter of
``st.markdown``.
disabled : bool or None
Whether editing should be disabled for this column. If this is ``None``
(default), Streamlit will enable editing wherever possible.
If a column has mixed types, it may become uneditable regardless of
``disabled``.
required : bool or None
Whether edited cells in the column need to have a value. If this is
``False`` (default), the user can submit empty values for this column.
If this is ``True``, an edited cell in this column can only be
submitted if its value is not ``None``, and a new row will only be
submitted after the user fills in this column.
pinned : bool or None
Whether the column is pinned. A pinned column will stay visible on the
left side no matter where the user scrolls. If this is ``None``
(default), Streamlit will decide: index columns are pinned, and data
columns are not pinned.
default : str, bool, int, float, or None
Specifies the default value in this column when a new row is added by
the user. This defaults to ``None``.
hidden : bool or None
Whether to hide the column. This defaults to ``False``.
type_config : dict or str or None
Configure a column type and type specific options.
"""
label: str | None
width: ColumnWidth | None
help: str | None
hidden: bool | None
disabled: bool | None
required: bool | None
pinned: bool | None
default: str | bool | int | float | list[str] | None
alignment: Literal["left", "center", "right"] | None
type_config: (
NumberColumnConfig
| TextColumnConfig
| CheckboxColumnConfig
| SelectboxColumnConfig
| LinkColumnConfig
| ListColumnConfig
| DatetimeColumnConfig
| DateColumnConfig
| TimeColumnConfig
| ProgressColumnConfig
| LineChartColumnConfig
| BarChartColumnConfig
| AreaChartColumnConfig
| ImageColumnConfig
| MultiselectColumnConfig
| JsonColumnConfig
| None
)
@gather_metrics("column_config.Column")
def Column(
label: str | None = None,
*,
width: ColumnWidth | None = None,
help: str | None = None,
disabled: bool | None = None,
required: bool | None = None,
pinned: bool | None = None,
) -> ColumnConfig:
"""Configure a generic column in ``st.dataframe`` or ``st.data_editor``.
The type of the column will be automatically inferred from the data type.
This command needs to be used in the ``column_config`` parameter of ``st.dataframe``
or ``st.data_editor``.
To change the type of the column and enable type-specific configuration options,
use one of the column types in the ``st.column_config`` namespace,
e.g. ``st.column_config.NumberColumn``.
Parameters
----------
label : str or None
The label shown at the top of the column. If this is ``None``
(default), the column name is used.
width : "small", "medium", "large", int, or None
The display width of the column. If this is ``None`` (default), the
column will be sized to fit the cell contents. Otherwise, this can be
one of the following:
- ``"small"``: 75px wide
- ``"medium"``: 200px wide
- ``"large"``: 400px wide
- An integer specifying the width in pixels
If the total width of all columns is less than the width of the
dataframe, the remaining space will be distributed evenly among all
columns.
help : str or None
A tooltip that gets displayed when hovering over the column label. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown, including
the Markdown directives described in the ``body`` parameter of
``st.markdown``.
disabled : bool or None
Whether editing should be disabled for this column. If this is ``None``
(default), Streamlit will enable editing wherever possible.
If a column has mixed types, it may become uneditable regardless of
``disabled``.
required : bool or None
Whether edited cells in the column need to have a value. If this is
``False`` (default), the user can submit empty values for this column.
If this is ``True``, an edited cell in this column can only be
submitted if its value is not ``None``, and a new row will only be
submitted after the user fills in this column.
pinned : bool or None
Whether the column is pinned. A pinned column will stay visible on the
left side no matter where the user scrolls. If this is ``None``
(default), Streamlit will decide: index columns are pinned, and data
columns are not pinned.
Examples
--------
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> data_df = pd.DataFrame(
>>> {
>>> "widgets": ["st.selectbox", "st.number_input", "st.text_area", "st.button"],
>>> }
>>> )
>>>
>>> st.data_editor(
>>> data_df,
>>> column_config={
>>> "widgets": st.column_config.Column(
>>> "Streamlit Widgets",
>>> help="Streamlit **widget** commands 🎈",
>>> width="medium",
>>> required=True,
>>> )
>>> },
>>> hide_index=True,
>>> num_rows="dynamic",
>>> )
.. output::
https://doc-column.streamlit.app/
height: 300px
"""
return ColumnConfig(
label=label,
width=width,
help=help,
disabled=disabled,
required=required,
pinned=pinned,
)
@gather_metrics("column_config.NumberColumn")
def NumberColumn(
label: str | None = None,
*,
width: ColumnWidth | None = None,
help: str | None = None,
disabled: bool | None = None,
required: bool | None = None,
pinned: bool | None = None,
default: int | float | None = None,
format: str | NumberFormat | None = None,
min_value: int | float | None = None,
max_value: int | float | None = None,
step: int | float | None = None,
) -> ColumnConfig:
"""Configure a number column in ``st.dataframe`` or ``st.data_editor``.
This is the default column type for integer and float values. This command needs to
be used in the ``column_config`` parameter of ``st.dataframe`` or ``st.data_editor``.
When used with ``st.data_editor``, editing will be enabled with a numeric input widget.
Parameters
----------
label : str or None
The label shown at the top of the column. If this is ``None``
(default), the column name is used.
width : "small", "medium", "large", int, or None
The display width of the column. If this is ``None`` (default), the
column will be sized to fit the cell contents. Otherwise, this can be
one of the following:
- ``"small"``: 75px wide
- ``"medium"``: 200px wide
- ``"large"``: 400px wide
- An integer specifying the width in pixels
If the total width of all columns is less than the width of the
dataframe, the remaining space will be distributed evenly among all
columns.
help : str or None
A tooltip that gets displayed when hovering over the column label. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown, including
the Markdown directives described in the ``body`` parameter of
``st.markdown``.
disabled : bool or None
Whether editing should be disabled for this column. If this is ``None``
(default), Streamlit will enable editing wherever possible.
If a column has mixed types, it may become uneditable regardless of
``disabled``.
required : bool or None
Whether edited cells in the column need to have a value. If this is
``False`` (default), the user can submit empty values for this column.
If this is ``True``, an edited cell in this column can only be
submitted if its value is not ``None``, and a new row will only be
submitted after the user fills in this column.
pinned : bool or None
Whether the column is pinned. A pinned column will stay visible on the
left side no matter where the user scrolls. If this is ``None``
(default), Streamlit will decide: index columns are pinned, and data
columns are not pinned.
default : int, float, or None
Specifies the default value in this column when a new row is added by
the user. This defaults to ``None``.
format : str, "plain", "localized", "percent", "dollar", "euro", "yen", "accounting", "compact", "scientific", "engineering", or None
A format string controlling how numbers are displayed.
This can be one of the following values:
- ``None`` (default): Streamlit infers the formatting from the data.
- ``"plain"``: Show the full number without any formatting (e.g. "1234.567").
- ``"localized"``: Show the number in the default locale format (e.g. "1,234.567").
- ``"percent"``: Show the number as a percentage (e.g. "123456.70%").
- ``"dollar"``: Show the number as a dollar amount (e.g. "$1,234.57").
- ``"euro"``: Show the number as a euro amount (e.g. "€1,234.57").
- ``"yen"``: Show the number as a yen amount (e.g. "¥1,235").
- ``"accounting"``: Show the number in an accounting format (e.g. "1,234.00").
- ``"bytes"``: Show the number in a byte format (e.g. "1.2KB").
- ``"compact"``: Show the number in a compact format (e.g. "1.2K").
- ``"scientific"``: Show the number in scientific notation (e.g. "1.235E3").
- ``"engineering"``: Show the number in engineering notation (e.g. "1.235E3").
- printf-style format string: Format the number with a printf
specifier, like ``"%d"`` to show a signed integer (e.g. "1234") or
``"%X"`` to show an unsigned hexadecimal integer (e.g. "4D2"). You
can also add prefixes and suffixes. To show British pounds, use
``"£ %.2f"`` (e.g. "£ 1234.57"). For more information, see `sprint-js
<https://github.com/alexei/sprintf.js?tab=readme-ov-file#format-specification>`_.
Formatting from ``column_config`` always takes precedence over
formatting from ``pandas.Styler``. The formatting does not impact the
return value when used in ``st.data_editor``.
min_value : int, float, or None
The minimum value that can be entered. If this is ``None`` (default),
there will be no minimum.
max_value : int, float, or None
The maximum value that can be entered. If this is ``None`` (default),
there will be no maximum.
step : int, float, or None
The precision of numbers that can be entered. If this ``None``
(default), integer columns will have a step of 1 and float columns will
have unrestricted precision. In this case, some floats may display like
integers. Setting ``step`` for float columns will ensure a consistent
number of digits after the decimal are displayed.
If ``format`` is a predefined format like ``"dollar"``, ``step``
overrides the display precision. If ``format`` is a printf-style format
string, ``step`` will not change the display precision.
Examples
--------
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> data_df = pd.DataFrame(
>>> {
>>> "price": [20, 950, 250, 500],
>>> }
>>> )
>>>
>>> st.data_editor(
>>> data_df,
>>> column_config={
>>> "price": st.column_config.NumberColumn(
>>> "Price (in USD)",
>>> help="The price of the product in USD",
>>> min_value=0,
>>> max_value=1000,
>>> step=1,
>>> format="$%d",
>>> )
>>> },
>>> hide_index=True,
>>> )
.. output::
https://doc-number-column.streamlit.app/
height: 300px
""" # noqa: E501
return ColumnConfig(
label=label,
width=width,
help=help,
disabled=disabled,
required=required,
pinned=pinned,
default=default,
type_config=NumberColumnConfig(
type="number",
min_value=min_value,
max_value=max_value,
format=format,
step=step,
),
)
@gather_metrics("column_config.TextColumn")
def TextColumn(
label: str | None = None,
*,
width: ColumnWidth | None = None,
help: str | None = None,
disabled: bool | None = None,
required: bool | None = None,
pinned: bool | None = None,
default: str | None = None,
max_chars: int | None = None,
validate: str | None = None,
) -> ColumnConfig:
r"""Configure a text column in ``st.dataframe`` or ``st.data_editor``.
This is the default column type for string values. This command needs to be used in the
``column_config`` parameter of ``st.dataframe`` or ``st.data_editor``. When used with
``st.data_editor``, editing will be enabled with a text input widget.
Parameters
----------
label : str or None
The label shown at the top of the column. If this is ``None``
(default), the column name is used.
width : "small", "medium", "large", int, or None
The display width of the column. If this is ``None`` (default), the
column will be sized to fit the cell contents. Otherwise, this can be
one of the following:
- ``"small"``: 75px wide
- ``"medium"``: 200px wide
- ``"large"``: 400px wide
- An integer specifying the width in pixels
If the total width of all columns is less than the width of the
dataframe, the remaining space will be distributed evenly among all
columns.
help : str or None
A tooltip that gets displayed when hovering over the column label. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown, including
the Markdown directives described in the ``body`` parameter of
``st.markdown``.
disabled : bool or None
Whether editing should be disabled for this column. If this is ``None``
(default), Streamlit will enable editing wherever possible.
If a column has mixed types, it may become uneditable regardless of
``disabled``.
required : bool or None
Whether edited cells in the column need to have a value. If this is
``False`` (default), the user can submit empty values for this column.
If this is ``True``, an edited cell in this column can only be
submitted if its value is not ``None``, and a new row will only be
submitted after the user fills in this column.
pinned : bool or None
Whether the column is pinned. A pinned column will stay visible on the
left side no matter where the user scrolls. If this is ``None``
(default), Streamlit will decide: index columns are pinned, and data
columns are not pinned.
default : str or None
Specifies the default value in this column when a new row is added by
the user. This defaults to ``None``.
max_chars : int or None
The maximum number of characters that can be entered. If this is
``None`` (default), there will be no maximum.
validate : str or None
A JS-flavored regular expression (e.g. ``"^[a-z]+$"``) that edited
values are validated against. If the user input is invalid, it will not
be submitted.
Examples
--------
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> data_df = pd.DataFrame(
>>> {
>>> "widgets": ["st.selectbox", "st.number_input", "st.text_area", "st.button"],
>>> }
>>> )
>>>
>>> st.data_editor(
>>> data_df,
>>> column_config={
>>> "widgets": st.column_config.TextColumn(
>>> "Widgets",
>>> help="Streamlit **widget** commands 🎈",
>>> default="st.",
>>> max_chars=50,
>>> validate=r"^st\.[a-z_]+$",
>>> )
>>> },
>>> hide_index=True,
>>> )
.. output::
https://doc-text-column.streamlit.app/
height: 300px
"""
return ColumnConfig(
label=label,
width=width,
help=help,
disabled=disabled,
required=required,
pinned=pinned,
default=default,
type_config=TextColumnConfig(
type="text", max_chars=max_chars, validate=validate
),
)
@gather_metrics("column_config.LinkColumn")
def LinkColumn(
label: str | None = None,
*,
width: ColumnWidth | None = None,
help: str | None = None,
disabled: bool | None = None,
required: bool | None = None,
pinned: bool | None = None,
default: str | None = None,
max_chars: int | None = None,
validate: str | None = None,
display_text: str | None = None,
) -> ColumnConfig:
r"""Configure a link column in ``st.dataframe`` or ``st.data_editor``.
The cell values need to be string and will be shown as clickable links.
This command needs to be used in the column_config parameter of ``st.dataframe``
or ``st.data_editor``. When used with ``st.data_editor``, editing will be enabled
with a text input widget.
Parameters
----------
label : str or None
The label shown at the top of the column. If this is ``None``
(default), the column name is used.
width : "small", "medium", "large", int, or None
The display width of the column. If this is ``None`` (default), the
column will be sized to fit the cell contents. Otherwise, this can be
one of the following:
- ``"small"``: 75px wide
- ``"medium"``: 200px wide
- ``"large"``: 400px wide
- An integer specifying the width in pixels
If the total width of all columns is less than the width of the
dataframe, the remaining space will be distributed evenly among all
columns.
help : str or None
A tooltip that gets displayed when hovering over the column label. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown, including
the Markdown directives described in the ``body`` parameter of
``st.markdown``.
disabled : bool or None
Whether editing should be disabled for this column. If this is ``None``
(default), Streamlit will enable editing wherever possible.
If a column has mixed types, it may become uneditable regardless of
``disabled``.
required : bool or None
Whether edited cells in the column need to have a value. If this is
``False`` (default), the user can submit empty values for this column.
If this is ``True``, an edited cell in this column can only be
submitted if its value is not ``None``, and a new row will only be
submitted after the user fills in this column.
pinned : bool or None
Whether the column is pinned. A pinned column will stay visible on the
left side no matter where the user scrolls. If this is ``None``
(default), Streamlit will decide: index columns are pinned, and data
columns are not pinned.
default : str or None
Specifies the default value in this column when a new row is added by
the user. This defaults to ``None``.
max_chars : int or None
The maximum number of characters that can be entered. If this is
``None`` (default), there will be no maximum.
validate : str or None
A JS-flavored regular expression (e.g. ``"^https://.+$"``) that edited
values are validated against. If the user input is invalid, it will not
be submitted.
display_text : str or None
The text that is displayed in the cell. This can be one of the
following:
- ``None`` (default) to display the URL itself.
- A string that is displayed in every cell, e.g. ``"Open link"``.
- A Material icon that is displayed in every cell, e.g. ``":material/open_in_new:"``.
- A JS-flavored regular expression (detected by usage of parentheses)
to extract a part of the URL via a capture group. For example, use
``"https://(.*?)\.example\.com"`` to extract the display text
"foo" from the URL "\https://foo.example.com".
.. Comment: The backslash in front of foo.example.com prevents a hyperlink in docs.
For more complex cases, you may use `Pandas Styler's format
<https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.format.html>`_
function on the underlying dataframe. Note that this makes the app slow,
doesn't work with editable columns, and might be removed in the future.
Text formatting from ``column_config`` always takes precedence over
text formatting from ``pandas.Styler``.
Examples
--------
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> data_df = pd.DataFrame(
>>> {
>>> "apps": [
>>> "https://roadmap.streamlit.app",
>>> "https://extras.streamlit.app",
>>> "https://issues.streamlit.app",
>>> "https://30days.streamlit.app",
>>> ],
>>> "creator": [
>>> "https://github.com/streamlit",
>>> "https://github.com/arnaudmiribel",
>>> "https://github.com/streamlit",
>>> "https://github.com/streamlit",
>>> ],
>>> }
>>> )
>>>
>>> st.data_editor(
>>> data_df,
>>> column_config={
>>> "apps": st.column_config.LinkColumn(
>>> "Trending apps",
>>> help="The top trending Streamlit apps",
>>> validate=r"^https://[a-z]+\.streamlit\.app$",
>>> max_chars=100,
>>> display_text=r"https://(.*?)\.streamlit\.app"
>>> ),
>>> "creator": st.column_config.LinkColumn(
>>> "App Creator", display_text="Open profile"
>>> ),
>>> },
>>> hide_index=True,
>>> )
.. output::
https://doc-link-column.streamlit.app/
height: 300px
"""
if display_text and display_text.startswith(":material/"):
display_text = validate_material_icon(display_text)
return ColumnConfig(
label=label,
width=width,
help=help,
disabled=disabled,
required=required,
pinned=pinned,
default=default,
type_config=LinkColumnConfig(
type="link",
max_chars=max_chars,
validate=validate,
display_text=display_text,
),
)
@gather_metrics("column_config.CheckboxColumn")
def CheckboxColumn(
label: str | None = None,
*,
width: ColumnWidth | None = None,
help: str | None = None,
disabled: bool | None = None,
required: bool | None = None,
pinned: bool | None = None,
default: bool | None = None,
) -> ColumnConfig:
"""Configure a checkbox column in ``st.dataframe`` or ``st.data_editor``.
This is the default column type for boolean values. This command needs to be used in
the ``column_config`` parameter of ``st.dataframe`` or ``st.data_editor``.
When used with ``st.data_editor``, editing will be enabled with a checkbox widget.
Parameters
----------
label : str or None
The label shown at the top of the column. If this is ``None``
(default), the column name is used.
width : "small", "medium", "large", int, or None
The display width of the column. If this is ``None`` (default), the
column will be sized to fit the cell contents. Otherwise, this can be
one of the following:
- ``"small"``: 75px wide
- ``"medium"``: 200px wide
- ``"large"``: 400px wide
- An integer specifying the width in pixels
If the total width of all columns is less than the width of the
dataframe, the remaining space will be distributed evenly among all
columns.
help : str or None
A tooltip that gets displayed when hovering over the column label. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown, including
the Markdown directives described in the ``body`` parameter of
``st.markdown``.
disabled : bool or None
Whether editing should be disabled for this column. If this is ``None``
(default), Streamlit will enable editing wherever possible.
If a column has mixed types, it may become uneditable regardless of
``disabled``.
required : bool or None
Whether edited cells in the column need to have a value. If this is
``False`` (default), the user can submit empty values for this column.
If this is ``True``, an edited cell in this column can only be
submitted if its value is not ``None``, and a new row will only be
submitted after the user fills in this column.
pinned : bool or None
Whether the column is pinned. A pinned column will stay visible on the
left side no matter where the user scrolls. If this is ``None``
(default), Streamlit will decide: index columns are pinned, and data
columns are not pinned.
default : bool or None
Specifies the default value in this column when a new row is added by
the user. This defaults to ``None``.
Examples
--------
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> data_df = pd.DataFrame(
>>> {
>>> "widgets": ["st.selectbox", "st.number_input", "st.text_area", "st.button"],
>>> "favorite": [True, False, False, True],
>>> }
>>> )
>>>
>>> st.data_editor(
>>> data_df,
>>> column_config={
>>> "favorite": st.column_config.CheckboxColumn(
>>> "Your favorite?",
>>> help="Select your **favorite** widgets",
>>> default=False,
>>> )
>>> },
>>> disabled=["widgets"],
>>> hide_index=True,
>>> )
.. output::
https://doc-checkbox-column.streamlit.app/
height: 300px
"""
return ColumnConfig(
label=label,
width=width,
help=help,
disabled=disabled,
required=required,
pinned=pinned,
default=default,
type_config=CheckboxColumnConfig(type="checkbox"),
)
@gather_metrics("column_config.SelectboxColumn")
def SelectboxColumn(
label: str | None = None,
*,
width: ColumnWidth | None = None,
help: str | None = None,
disabled: bool | None = None,
required: bool | None = None,
pinned: bool | None = None,
default: SelectboxOptionValue | None = None,
options: Iterable[SelectboxOptionValue] | None = None,
format_func: Callable[[SelectboxOptionValue], str] | None = None,
) -> ColumnConfig:
"""Configure a selectbox column in ``st.dataframe`` or ``st.data_editor``.
This is the default column type for Pandas categorical values. This command needs to
be used in the ``column_config`` parameter of ``st.dataframe`` or ``st.data_editor``.
When used with ``st.data_editor``, editing will be enabled with a selectbox widget.
Parameters
----------
label : str or None
The label shown at the top of the column. If this is ``None``
(default), the column name is used.
width : "small", "medium", "large", int, or None
The display width of the column. If this is ``None`` (default), the
column will be sized to fit the cell contents. Otherwise, this can be
one of the following:
- ``"small"``: 75px wide
- ``"medium"``: 200px wide
- ``"large"``: 400px wide
- An integer specifying the width in pixels
If the total width of all columns is less than the width of the
dataframe, the remaining space will be distributed evenly among all
columns.
help : str or None
A tooltip that gets displayed when hovering over the column label. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown, including
the Markdown directives described in the ``body`` parameter of
``st.markdown``.
disabled : bool or None
Whether editing should be disabled for this column. If this is ``None``
(default), Streamlit will enable editing wherever possible.
If a column has mixed types, it may become uneditable regardless of
``disabled``.
required : bool or None
Whether edited cells in the column need to have a value. If this is
``False`` (default), the user can submit empty values for this column.
If this is ``True``, an edited cell in this column can only be
submitted if its value is not ``None``, and a new row will only be
submitted after the user fills in this column.
pinned : bool or None
Whether the column is pinned. A pinned column will stay visible on the
left side no matter where the user scrolls. If this is ``None``
(default), Streamlit will decide: index columns are pinned, and data
columns are not pinned.
default : str, int, float, bool, or None
Specifies the default value in this column when a new row is added by
the user. This defaults to ``None``.
options : Iterable[str, int, float, bool] or None
The options that can be selected during editing. If this is ``None``
(default), the options will be inferred from the underlying dataframe
column if its dtype is "category". For more information, see `Pandas docs
<https://pandas.pydata.org/docs/user_guide/categorical.html>`_).
format_func : function or None
Function to modify the display of the options. It receives
the raw option defined in ``options`` as an argument and should output
the label to be shown for that option. If this is ``None`` (default),
the raw option is used as the label.
Examples
--------
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> data_df = pd.DataFrame(
>>> {
>>> "category": [
>>> "📊 Data Exploration",
>>> "📈 Data Visualization",
>>> "🤖 LLM",
>>> "📊 Data Exploration",
>>> ],
>>> }
>>> )
>>>
>>> st.data_editor(
>>> data_df,
>>> column_config={
>>> "category": st.column_config.SelectboxColumn(
>>> "App Category",
>>> help="The category of the app",
>>> width="medium",
>>> options=[
>>> "📊 Data Exploration",
>>> "📈 Data Visualization",
>>> "🤖 LLM",
>>> ],
>>> required=True,
>>> )
>>> },
>>> hide_index=True,
>>> )
.. output::
https://doc-selectbox-column.streamlit.app/
height: 300px
"""
# Process options with format_func
processed_options: Iterable[str | int | float | SelectboxOption] | None = options
if options and format_func is not None:
processed_options = []
for option in options:
processed_options.append(
SelectboxOption(value=option, label=format_func(option))
)
return ColumnConfig(
label=label,
width=width,
help=help,
disabled=disabled,
required=required,
pinned=pinned,
default=default,
type_config=SelectboxColumnConfig(
type="selectbox",
options=list(processed_options) if processed_options is not None else None,
),
)
@gather_metrics("column_config.BarChartColumn")
def BarChartColumn(
label: str | None = None,
*,
width: ColumnWidth | None = None,
help: str | None = None,
pinned: bool | None = None,
y_min: int | float | None = None,
y_max: int | float | None = None,
color: ChartColor | None = None,
) -> ColumnConfig:
"""Configure a bar chart column in ``st.dataframe`` or ``st.data_editor``.
Cells need to contain a list of numbers. Chart columns are not editable
at the moment. This command needs to be used in the ``column_config`` parameter
of ``st.dataframe`` or ``st.data_editor``.
Parameters
----------
label : str or None
The label shown at the top of the column. If this is ``None``
(default), the column name is used.
width : "small", "medium", "large", int, or None
The display width of the column. If this is ``None`` (default), the
column will be sized to fit the cell contents. Otherwise, this can be
one of the following:
- ``"small"``: 75px wide
- ``"medium"``: 200px wide
- ``"large"``: 400px wide
- An integer specifying the width in pixels
If the total width of all columns is less than the width of the
dataframe, the remaining space will be distributed evenly among all
columns.
help : str or None
A tooltip that gets displayed when hovering over the column label. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown, including
the Markdown directives described in the ``body`` parameter of
``st.markdown``.
pinned: bool or None
Whether the column is pinned. A pinned column will stay visible on the
left side no matter where the user scrolls. If this is ``None``
(default), Streamlit will decide: index columns are pinned, and data
columns are not pinned.
y_min : int, float, or None
The minimum value on the y-axis for all cells in the column. If this is
``None`` (default), every cell will use the minimum of its data.
y_max : int, float, or None
The maximum value on the y-axis for all cells in the column. If this is
``None`` (default), every cell will use the maximum of its data.
color : "auto", "auto-inverse", str, or None
The color to use for the chart. This can be one of the following:
- ``None`` (default): The primary color is used.
- ``"auto"``: If the data is increasing, the chart is green; if the
data is decreasing, the chart is red.
- ``"auto-inverse"``: If the data is increasing, the chart is red; if
the data is decreasing, the chart is green.
- A single color value that is applied to all charts in the column.
In addition to the basic color palette (red, orange, yellow, green,
blue, violet, gray/grey, and primary), this supports hex codes like
``"#483d8b"``.
Examples
--------
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> data_df = pd.DataFrame(
>>> {
>>> "sales": [
>>> [0, 4, 26, 80, 100, 40],
>>> [80, 20, 80, 35, 40, 100],
>>> [10, 20, 80, 80, 70, 0],
>>> [10, 100, 20, 100, 30, 100],
>>> ],
>>> }
>>> )
>>>
>>> st.data_editor(
>>> data_df,
>>> column_config={
>>> "sales": st.column_config.BarChartColumn(
>>> "Sales (last 6 months)",
>>> help="The sales volume in the last 6 months",
>>> y_min=0,
>>> y_max=100,
>>> ),
>>> },
>>> hide_index=True,
>>> )
.. output::
https://doc-barchart-column.streamlit.app/
height: 300px
"""
if color is not None:
_validate_chart_color(color)
return ColumnConfig(
label=label,
width=width,
help=help,
pinned=pinned,
type_config=BarChartColumnConfig(
type="bar_chart", y_min=y_min, y_max=y_max, color=color
),
)
@gather_metrics("column_config.LineChartColumn")
def LineChartColumn(
label: str | None = None,
*,
width: ColumnWidth | None = None,
help: str | None = None,
pinned: bool | None = None,
y_min: int | float | None = None,
y_max: int | float | None = None,
color: ChartColor | None = None,
) -> ColumnConfig:
"""Configure a line chart column in ``st.dataframe`` or ``st.data_editor``.
Cells need to contain a list of numbers. Chart columns are not editable
at the moment. This command needs to be used in the ``column_config`` parameter
of ``st.dataframe`` or ``st.data_editor``.
Parameters
----------
label : str or None
The label shown at the top of the column. If this is ``None``
(default), the column name is used.
width : "small", "medium", "large", int, or None
The display width of the column. If this is ``None`` (default), the
column will be sized to fit the cell contents. Otherwise, this can be
one of the following:
- ``"small"``: 75px wide
- ``"medium"``: 200px wide
- ``"large"``: 400px wide
- An integer specifying the width in pixels
If the total width of all columns is less than the width of the
dataframe, the remaining space will be distributed evenly among all
columns.
help : str or None
A tooltip that gets displayed when hovering over the column label. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown, including
the Markdown directives described in the ``body`` parameter of
``st.markdown``.
pinned : bool or None
Whether the column is pinned. A pinned column will stay visible on the
left side no matter where the user scrolls. If this is ``None``
(default), Streamlit will decide: index columns are pinned, and data
columns are not pinned.
y_min : int, float, or None
The minimum value on the y-axis for all cells in the column. If this is
``None`` (default), every cell will use the minimum of its data.
y_max : int, float, or None
The maximum value on the y-axis for all cells in the column. If this is
``None`` (default), every cell will use the maximum of its data.
color : "auto", "auto-inverse", str, or None
The color to use for the chart. This can be one of the following:
- ``None`` (default): The primary color is used.
- ``"auto"``: If the data is increasing, the chart is green; if the
data is decreasing, the chart is red.
- ``"auto-inverse"``: If the data is increasing, the chart is red; if
the data is decreasing, the chart is green.
- A single color value that is applied to all charts in the column.
In addition to the basic color palette (red, orange, yellow, green,
blue, violet, gray/grey, and primary), this supports hex codes like
``"#483d8b"``.
Examples
--------
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> data_df = pd.DataFrame(
>>> {
>>> "sales": [
>>> [0, 4, 26, 80, 100, 40],
>>> [80, 20, 80, 35, 40, 100],
>>> [10, 20, 80, 80, 70, 0],
>>> [10, 100, 20, 100, 30, 100],
>>> ],
>>> }
>>> )
>>>
>>> st.data_editor(
>>> data_df,
>>> column_config={
>>> "sales": st.column_config.LineChartColumn(
>>> "Sales (last 6 months)",
>>> width="medium",
>>> help="The sales volume in the last 6 months",
>>> y_min=0,
>>> y_max=100,
>>> ),
>>> },
>>> hide_index=True,
>>> )
.. output::
https://doc-linechart-column.streamlit.app/
height: 300px
"""
if color is not None:
_validate_chart_color(color)
return ColumnConfig(
label=label,
width=width,
help=help,
pinned=pinned,
type_config=LineChartColumnConfig(
type="line_chart", y_min=y_min, y_max=y_max, color=color
),
)
@gather_metrics("column_config.AreaChartColumn")
def AreaChartColumn(
label: str | None = None,
*,
width: ColumnWidth | None = None,
help: str | None = None,
pinned: bool | None = None,
y_min: int | float | None = None,
y_max: int | float | None = None,
color: ChartColor | None = None,
) -> ColumnConfig:
"""Configure an area chart column in ``st.dataframe`` or ``st.data_editor``.
Cells need to contain a list of numbers. Chart columns are not editable
at the moment. This command needs to be used in the ``column_config`` parameter
of ``st.dataframe`` or ``st.data_editor``.
Parameters
----------
label : str or None
The label shown at the top of the column. If this is ``None``
(default), the column name is used.
width : "small", "medium", "large", int, or None
The display width of the column. If this is ``None`` (default), the
column will be sized to fit the cell contents. Otherwise, this can be
one of the following:
- ``"small"``: 75px wide
- ``"medium"``: 200px wide
- ``"large"``: 400px wide
- An integer specifying the width in pixels
If the total width of all columns is less than the width of the
dataframe, the remaining space will be distributed evenly among all
columns.
help : str or None
A tooltip that gets displayed when hovering over the column label. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown, including
the Markdown directives described in the ``body`` parameter of
``st.markdown``.
pinned : bool or None
Whether the column is pinned. A pinned column will stay visible on the
left side no matter where the user scrolls. If this is ``None``
(default), Streamlit will decide: index columns are pinned, and data
columns are not pinned.
y_min : int, float, or None
The minimum value on the y-axis for all cells in the column. If this is
``None`` (default), every cell will use the minimum of its data.
y_max : int, float, or None
The maximum value on the y-axis for all cells in the column. If this is
``None`` (default), every cell will use the maximum of its data.
color : "auto", "auto-inverse", str, or None
The color to use for the chart. This can be one of the following:
- ``None`` (default): The primary color is used.
- ``"auto"``: If the data is increasing, the chart is green; if the
data is decreasing, the chart is red.
- ``"auto-inverse"``: If the data is increasing, the chart is red; if
the data is decreasing, the chart is green.
- A single color value that is applied to all charts in the column.
In addition to the basic color palette (red, orange, yellow, green,
blue, violet, gray/grey, and primary), this supports hex codes like
``"#483d8b"``.
The basic color palette can be configured in the theme settings.
Examples
--------
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> data_df = pd.DataFrame(
>>> {
>>> "sales": [
>>> [0, 4, 26, 80, 100, 40],
>>> [80, 20, 80, 35, 40, 100],
>>> [10, 20, 80, 80, 70, 0],
>>> [10, 100, 20, 100, 30, 100],
>>> ],
>>> }
>>> )
>>>
>>> st.data_editor(
>>> data_df,
>>> column_config={
>>> "sales": st.column_config.AreaChartColumn(
>>> "Sales (last 6 months)",
>>> width="medium",
>>> help="The sales volume in the last 6 months",
>>> y_min=0,
>>> y_max=100,
>>> ),
>>> },
>>> hide_index=True,
>>> )
.. output::
https://doc-areachart-column.streamlit.app/
height: 300px
"""
if color is not None:
_validate_chart_color(color)
return ColumnConfig(
label=label,
width=width,
help=help,
pinned=pinned,
type_config=AreaChartColumnConfig(
type="area_chart", y_min=y_min, y_max=y_max, color=color
),
)
@gather_metrics("column_config.ImageColumn")
def ImageColumn(
label: str | None = None,
*,
width: ColumnWidth | None = None,
help: str | None = None,
pinned: bool | None = None,
) -> ColumnConfig:
"""Configure an image column in ``st.dataframe`` or ``st.data_editor``.
The cell values need to be one of:
* A URL to fetch the image from. This can also be a relative URL of an image
deployed via `static file serving <https://docs.streamlit.io/develop/concepts/configuration/serving-static-files>`_.
Note that you can NOT use an arbitrary local image if it is not available through
a public URL.
* A data URL containing an SVG XML like ``data:image/svg+xml;utf8,<svg xmlns=...</svg>``.
* A data URL containing a Base64 encoded image like ``data:image/png;base64,iVBO...``.
Image columns are not editable at the moment. This command needs to be used in the
``column_config`` parameter of ``st.dataframe`` or ``st.data_editor``.
Parameters
----------
label : str or None
The label shown at the top of the column. If this is ``None``
(default), the column name is used.
width : "small", "medium", "large", int, or None
The display width of the column. If this is ``None`` (default), the
column will be sized to fit the cell contents. Otherwise, this can be
one of the following:
- ``"small"``: 75px wide
- ``"medium"``: 200px wide
- ``"large"``: 400px wide
- An integer specifying the width in pixels
If the total width of all columns is less than the width of the
dataframe, the remaining space will be distributed evenly among all
columns.
help : str or None
A tooltip that gets displayed when hovering over the column label. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown, including
the Markdown directives described in the ``body`` parameter of
``st.markdown``.
pinned : bool or None
Whether the column is pinned. A pinned column will stay visible on the
left side no matter where the user scrolls. If this is ``None``
(default), Streamlit will decide: index columns are pinned, and data
columns are not pinned.
Examples
--------
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> data_df = pd.DataFrame(
>>> {
>>> "apps": [
>>> "https://storage.googleapis.com/s4a-prod-share-preview/default/st_app_screenshot_image/5435b8cb-6c6c-490b-9608-799b543655d3/Home_Page.png",
>>> "https://storage.googleapis.com/s4a-prod-share-preview/default/st_app_screenshot_image/ef9a7627-13f2-47e5-8f65-3f69bb38a5c2/Home_Page.png",
>>> "https://storage.googleapis.com/s4a-prod-share-preview/default/st_app_screenshot_image/31b99099-8eae-4ff8-aa89-042895ed3843/Home_Page.png",
>>> "https://storage.googleapis.com/s4a-prod-share-preview/default/st_app_screenshot_image/6a399b09-241e-4ae7-a31f-7640dc1d181e/Home_Page.png",
>>> ],
>>> }
>>> )
>>>
>>> st.data_editor(
>>> data_df,
>>> column_config={
>>> "apps": st.column_config.ImageColumn(
>>> "Preview Image", help="Streamlit app preview screenshots"
>>> )
>>> },
>>> hide_index=True,
>>> )
.. output::
https://doc-image-column.streamlit.app/
height: 300px
"""
return ColumnConfig(
label=label,
width=width,
help=help,
pinned=pinned,
type_config=ImageColumnConfig(type="image"),
)
@gather_metrics("column_config.ListColumn")
def ListColumn(
label: str | None = None,
*,
width: ColumnWidth | None = None,
help: str | None = None,
pinned: bool | None = None,
disabled: bool | None = None,
required: bool | None = None,
default: Iterable[str] | None = None,
) -> ColumnConfig:
"""Configure a list column in ``st.dataframe`` or ``st.data_editor``.
This is the default column type for list-like values. This command needs to
be used in the ``column_config`` parameter of ``st.dataframe`` or
``st.data_editor``. When used with ``st.data_editor``, users can freely
type in new options and remove existing ones.
.. Note::
Editing for non-string or mixed type lists can cause issues with Arrow
serialization. We recommend that you disable editing for these columns
or convert all list values to strings.
Parameters
----------
label : str or None
The label shown at the top of the column. If this is ``None``
(default), the column name is used.
width : "small", "medium", "large", int, or None
The display width of the column. If this is ``None`` (default), the
column will be sized to fit the cell contents. Otherwise, this can be
one of the following:
- ``"small"``: 75px wide
- ``"medium"``: 200px wide
- ``"large"``: 400px wide
- An integer specifying the width in pixels
If the total width of all columns is less than the width of the
dataframe, the remaining space will be distributed evenly among all
columns.
help : str or None
A tooltip that gets displayed when hovering over the column label. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown, including
the Markdown directives described in the ``body`` parameter of
``st.markdown``.
pinned : bool or None
Whether the column is pinned. A pinned column will stay visible on the
left side no matter where the user scrolls. If this is ``None``
(default), Streamlit will decide: index columns are pinned, and data
columns are not pinned.
disabled : bool or None
Whether editing should be disabled for this column. If this is ``None``
(default), Streamlit will enable editing wherever possible.
If a column has mixed types, it may become uneditable regardless of
``disabled``.
required : bool or None
Whether edited cells in the column need to have a value. If this is
``False`` (default), the user can submit empty values for this column.
If this is ``True``, an edited cell in this column can only be
submitted if its value is not ``None``, and a new row will only be
submitted after the user fills in this column.
default : Iterable of str or None
Specifies the default value in this column when a new row is added by
the user. This defaults to ``None``.
Examples
--------
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> data_df = pd.DataFrame(
>>> {
>>> "sales": [
>>> [0, 4, 26, 80, 100, 40],
>>> [80, 20, 80, 35, 40, 100],
>>> [10, 20, 80, 80, 70, 0],
>>> [10, 100, 20, 100, 30, 100],
>>> ],
>>> }
>>> )
>>>
>>> st.data_editor(
>>> data_df,
>>> column_config={
>>> "sales": st.column_config.ListColumn(
>>> "Sales (last 6 months)",
>>> help="The sales volume in the last 6 months",
>>> width="medium",
>>> ),
>>> },
>>> hide_index=True,
>>> )
.. output::
https://doc-list-column.streamlit.app/
height: 300px
"""
return ColumnConfig(
label=label,
width=width,
help=help,
pinned=pinned,
disabled=disabled,
required=required,
default=None if default is None else list(default),
type_config=ListColumnConfig(type="list"),
)
@gather_metrics("column_config.MultiselectColumn")
def MultiselectColumn(
label: str | None = None,
*,
width: ColumnWidth | None = None,
help: str | None = None,
disabled: bool | None = None,
required: bool | None = None,
pinned: bool | None = None,
default: Iterable[str] | None = None,
options: Iterable[str] | None = None,
accept_new_options: bool | None = None,
color: str
| Literal["auto"]
| ThemeColor
| Iterable[str | ThemeColor]
| None = None,
format_func: Callable[[str], str] | None = None,
) -> ColumnConfig:
"""Configure a multiselect column in ``st.dataframe`` or ``st.data_editor``.
This command needs to be used in the ``column_config`` parameter of
``st.dataframe`` or ``st.data_editor``. When used with ``st.data_editor``,
users can select options from a dropdown menu. You can configure the
column to allow freely typed options, too.
You can also use this column type to display colored labels in a read-only
``st.dataframe``.
.. Note::
Editing for non-string or mixed type lists can cause issues with Arrow
serialization. We recommend that you disable editing for these columns
or convert all list values to strings.
Parameters
----------
label : str or None
The label shown at the top of the column. If None (default),
the column name is used.
width : "small", "medium", "large", or None
The display width of the column. If this is ``None`` (default), the
column will be sized to fit the cell contents. Otherwise, this can be
one of the following:
- ``"small"``: 75px wide
- ``"medium"``: 200px wide
- ``"large"``: 400px wide
- An integer specifying the width in pixels
If the total width of all columns is less than the width of the
dataframe, the remaining space will be distributed evenly among all
columns.
help : str or None
A tooltip that gets displayed when hovering over the column label. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown, including
the Markdown directives described in the ``body`` parameter of
``st.markdown``.
disabled : bool or None
Whether editing should be disabled for this column. Defaults to False.
required : bool or None
Whether edited cells in the column need to have a value. If True, an edited cell
can only be submitted if it has a value other than None. Defaults to False.
pinned : bool or None
Whether the column is pinned. A pinned column will stay visible on the
left side no matter where the user scrolls. If this is ``None``
(default), Streamlit will decide: index columns are pinned, and data
columns are not pinned.
default : Iterable of str or None
Specifies the default value in this column when a new row is added by the user.
options : Iterable of str or None
The options that can be selected during editing.
accept_new_options : bool or None
Whether the user can add selections that aren't included in ``options``.
If this is ``False`` (default), the user can only select from the
items in ``options``. If this is ``True``, the user can enter new
items that don't exist in ``options``.
When a user enters and selects a new item, it is included in the
returned cell list value as a string. The new item is not added to
the options drop-down menu.
color : str, Iterable of str, or None
The color to use for different options. This can be:
- None (default): The options are displayed without color.
- ``"auto"``: The options are colored based on the configured categorical chart colors.
- A single color value that is used for all options. This can be one of
the following strings:
- ``"primary"`` to use the primary theme color.
- A CSS named color name like ``"darkBlue"`` or ``"maroon"``.
- A hex color code like ``"#483d8b"`` or ``"#6A5ACD80"``.
- An RGB or RGBA color code like ``"rgb(255,0,0)"`` or
``"RGB(70, 130, 180, .7)"``.
- An HSL or HSLA color code like ``"hsl(248, 53%, 58%)"``
or ``"HSL(147, 50%, 47%, .3)"``.
- An iterable of color values that are mapped to the options. The colors
are applied in sequence, cycling through the iterable if there are
more options than colors.
format_func : function or None
Function to modify the display of the options. It receives
the raw option defined in ``options`` as an argument and should output
the label to be shown for that option. When used in ``st.data_editor``,
this has no impact on the returned value. If this is ``None``
(default), the raw option is used as the label.
Examples
--------
**Example 1: Editable multiselect column**
To customize the label colors, provide a list of colors to the ``color``
parameter. You can also format the option labels with the ``format_func``
parameter.
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> data_df = pd.DataFrame(
... {
... "category": [
... ["exploration", "visualization"],
... ["llm", "visualization"],
... ["exploration"],
... ],
... }
... )
>>>
>>> st.data_editor(
... data_df,
... column_config={
... "category": st.column_config.MultiselectColumn(
... "App Categories",
... help="The categories of the app",
... options=[
... "exploration",
... "visualization",
... "llm",
... ],
... color=["#ffa421", "#803df5", "#00c0f2"],
... format_func=lambda x: x.capitalize(),
... ),
... },
... )
.. output::
https://doc-multiselect-column-1.streamlit.app/
height: 300px
**Example 2: Colored tags for st.dataframe**
When using ``st.dataframe``, the multiselect column is read-only
and can be used to display colored tags. In this example, the dataframe
uses the primary theme color for all tags.
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> data_df = pd.DataFrame(
... {
... "category": [
... ["exploration", "visualization"],
... ["llm", "visualization"],
... ["exploration"],
... ],
... }
... )
>>>
>>> st.dataframe(
... data_df,
... column_config={
... "category": st.column_config.MultiselectColumn(
... "App Categories",
... options=["exploration", "visualization", "llm"],
... color="primary",
... format_func=lambda x: x.capitalize(),
... ),
... },
... )
.. output::
https://doc-multiselect-column-2.streamlit.app/
height: 300px
"""
# Process options with color and format_func:
processed_options: list[MultiselectOption] | None = None
if options is not None:
processed_options = []
# Convert color to an iterator
color_iter: Iterator[str] | None = None
if color is not None:
if isinstance(color, str):
# Single color for all options
color_iter = itertools.repeat(color)
else:
# Iterable of colors - cycle through them
color_iter = itertools.cycle(color)
for option in options:
# Start with the option value
option_dict = MultiselectOption(value=option)
# Apply format_func to generate label if not already present
if format_func is not None:
option_dict["label"] = format_func(option_dict["value"])
# Apply color if provided and not already present
if color_iter is not None and "color" not in option_dict:
option_dict["color"] = next(color_iter)
processed_options.append(option_dict)
return ColumnConfig(
label=label,
width=width,
help=help,
disabled=disabled,
required=required,
pinned=pinned,
default=None if default is None else list(default),
type_config=MultiselectColumnConfig(
type="multiselect",
options=processed_options,
accept_new_options=accept_new_options,
),
)
@gather_metrics("column_config.DatetimeColumn")
def DatetimeColumn(
label: str | None = None,
*,
width: ColumnWidth | None = None,
help: str | None = None,
disabled: bool | None = None,
required: bool | None = None,
pinned: bool | None = None,
default: datetime.datetime | None = None,
format: str | Literal["localized", "distance", "calendar", "iso8601"] | None = None,
min_value: datetime.datetime | None = None,
max_value: datetime.datetime | None = None,
step: int | float | datetime.timedelta | None = None,
timezone: str | None = None,
) -> ColumnConfig:
"""Configure a datetime column in ``st.dataframe`` or ``st.data_editor``.
This is the default column type for datetime values. This command needs to be
used in the ``column_config`` parameter of ``st.dataframe`` or
``st.data_editor``. When used with ``st.data_editor``, editing will be enabled
with a datetime picker widget.
Parameters
----------
label : str or None
The label shown at the top of the column. If this is ``None``
(default), the column name is used.
width : "small", "medium", "large", int, or None
The display width of the column. If this is ``None`` (default), the
column will be sized to fit the cell contents. Otherwise, this can be
one of the following:
- ``"small"``: 75px wide
- ``"medium"``: 200px wide
- ``"large"``: 400px wide
- An integer specifying the width in pixels
If the total width of all columns is less than the width of the
dataframe, the remaining space will be distributed evenly among all
columns.
help : str or None
A tooltip that gets displayed when hovering over the column label. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown, including
the Markdown directives described in the ``body`` parameter of
``st.markdown``.
disabled : bool or None
Whether editing should be disabled for this column. If this is ``None``
(default), Streamlit will enable editing wherever possible.
If a column has mixed types, it may become uneditable regardless of
``disabled``.
required : bool or None
Whether edited cells in the column need to have a value. If this is
``False`` (default), the user can submit empty values for this column.
If this is ``True``, an edited cell in this column can only be
submitted if its value is not ``None``, and a new row will only be
submitted after the user fills in this column.
pinned : bool or None
Whether the column is pinned. A pinned column will stay visible on the
left side no matter where the user scrolls. If this is ``None``
(default), Streamlit will decide: index columns are pinned, and data
columns are not pinned.
default : datetime.datetime or None
Specifies the default value in this column when a new row is added by
the user. This defaults to ``None``.
format : str, "localized", "distance", "calendar", "iso8601", or None
A format string controlling how datetimes are displayed.
This can be one of the following values:
- ``None`` (default): Show the datetime in ``"YYYY-MM-DD HH:mm:ss"``
format (e.g. "2025-03-04 20:00:00").
- ``"localized"``: Show the datetime in the default locale format (e.g.
"Mar 4, 2025, 12:00:00 PM" in the America/Los_Angeles timezone).
- ``"distance"``: Show the datetime in a relative format (e.g.
"a few seconds ago").
- ``"calendar"``: Show the datetime in a calendar format (e.g.
"Today at 8:00 PM").
- ``"iso8601"``: Show the datetime in ISO 8601 format (e.g.
"2025-03-04T20:00:00.000Z").
- A momentJS format string: Format the datetime with a string, like
``"ddd ha"`` to show "Tue 8pm". For available formats, see
`momentJS <https://momentjs.com/docs/#/displaying/format/>`_.
Formatting from ``column_config`` always takes precedence over
formatting from ``pandas.Styler``. The formatting does not impact the
return value when used in ``st.data_editor``.
min_value : datetime.datetime or None
The minimum datetime that can be entered. If this is ``None``
(default), there will be no minimum.
max_value : datetime.datetime or None
The maximum datetime that can be entered. If this is ``None``
(default), there will be no maximum.
step : int, float, datetime.timedelta, or None
The stepping interval in seconds. If this is ``None`` (default), the
step will be 1 second.
timezone : str or None
The timezone of this column. If this is ``None`` (default), the
timezone is inferred from the underlying data.
Examples
--------
>>> from datetime import datetime
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> data_df = pd.DataFrame(
>>> {
>>> "appointment": [
>>> datetime(2024, 2, 5, 12, 30),
>>> datetime(2023, 11, 10, 18, 0),
>>> datetime(2024, 3, 11, 20, 10),
>>> datetime(2023, 9, 12, 3, 0),
>>> ]
>>> }
>>> )
>>>
>>> st.data_editor(
>>> data_df,
>>> column_config={
>>> "appointment": st.column_config.DatetimeColumn(
>>> "Appointment",
>>> min_value=datetime(2023, 6, 1),
>>> max_value=datetime(2025, 1, 1),
>>> format="D MMM YYYY, h:mm a",
>>> step=60,
>>> ),
>>> },
>>> hide_index=True,
>>> )
.. output::
https://doc-datetime-column.streamlit.app/
height: 300px
"""
return ColumnConfig(
label=label,
width=width,
help=help,
disabled=disabled,
required=required,
pinned=pinned,
default=None if default is None else default.isoformat(),
type_config=DatetimeColumnConfig(
type="datetime",
format=format,
min_value=None if min_value is None else min_value.isoformat(),
max_value=None if max_value is None else max_value.isoformat(),
step=step.total_seconds() if isinstance(step, datetime.timedelta) else step,
timezone=timezone,
),
)
@gather_metrics("column_config.TimeColumn")
def TimeColumn(
label: str | None = None,
*,
width: ColumnWidth | None = None,
help: str | None = None,
disabled: bool | None = None,
required: bool | None = None,
pinned: bool | None = None,
default: datetime.time | None = None,
format: str | Literal["localized", "iso8601"] | None = None,
min_value: datetime.time | None = None,
max_value: datetime.time | None = None,
step: int | float | datetime.timedelta | None = None,
) -> ColumnConfig:
"""Configure a time column in ``st.dataframe`` or ``st.data_editor``.
This is the default column type for time values. This command needs to be used in
the ``column_config`` parameter of ``st.dataframe`` or ``st.data_editor``. When
used with ``st.data_editor``, editing will be enabled with a time picker widget.
Parameters
----------
label : str or None
The label shown at the top of the column. If this is ``None``
(default), the column name is used.
width : "small", "medium", "large", int, or None
The display width of the column. If this is ``None`` (default), the
column will be sized to fit the cell contents. Otherwise, this can be
one of the following:
- ``"small"``: 75px wide
- ``"medium"``: 200px wide
- ``"large"``: 400px wide
- An integer specifying the width in pixels
If the total width of all columns is less than the width of the
dataframe, the remaining space will be distributed evenly among all
columns.
help : str or None
A tooltip that gets displayed when hovering over the column label. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown, including
the Markdown directives described in the ``body`` parameter of
``st.markdown``.
disabled : bool or None
Whether editing should be disabled for this column. If this is ``None``
(default), Streamlit will enable editing wherever possible.
If a column has mixed types, it may become uneditable regardless of
``disabled``.
required : bool or None
Whether edited cells in the column need to have a value. If this is
``False`` (default), the user can submit empty values for this column.
If this is ``True``, an edited cell in this column can only be
submitted if its value is not ``None``, and a new row will only be
submitted after the user fills in this column.
pinned : bool or None
Whether the column is pinned. A pinned column will stay visible on the
left side no matter where the user scrolls. If this is ``None``
(default), Streamlit will decide: index columns are pinned, and data
columns are not pinned.
default : datetime.time or None
Specifies the default value in this column when a new row is added by
the user. This defaults to ``None``.
format : str, "localized", "iso8601", or None
A format string controlling how times are displayed.
This can be one of the following values:
- ``None`` (default): Show the time in ``"HH:mm:ss"`` format (e.g.
"20:00:00").
- ``"localized"``: Show the time in the default locale format (e.g.
"12:00:00 PM" in the America/Los_Angeles timezone).
- ``"iso8601"``: Show the time in ISO 8601 format (e.g.
"20:00:00.000Z").
- A momentJS format string: Format the time with a string, like
``"ha"`` to show "8pm". For available formats, see
`momentJS <https://momentjs.com/docs/#/displaying/format/>`_.
Formatting from ``column_config`` always takes precedence over
formatting from ``pandas.Styler``. The formatting does not impact the
return value when used in ``st.data_editor``.
min_value : datetime.time or None
The minimum time that can be entered. If this is ``None`` (default),
there will be no minimum.
max_value : datetime.time or None
The maximum time that can be entered. If this is ``None`` (default),
there will be no maximum.
step : int, float, datetime.timedelta, or None
The stepping interval in seconds. If this is ``None`` (default), the
step will be 1 second.
Examples
--------
>>> from datetime import time
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> data_df = pd.DataFrame(
>>> {
>>> "appointment": [
>>> time(12, 30),
>>> time(18, 0),
>>> time(9, 10),
>>> time(16, 25),
>>> ]
>>> }
>>> )
>>>
>>> st.data_editor(
>>> data_df,
>>> column_config={
>>> "appointment": st.column_config.TimeColumn(
>>> "Appointment",
>>> min_value=time(8, 0, 0),
>>> max_value=time(19, 0, 0),
>>> format="hh:mm a",
>>> step=60,
>>> ),
>>> },
>>> hide_index=True,
>>> )
.. output::
https://doc-time-column.streamlit.app/
height: 300px
"""
return ColumnConfig(
label=label,
width=width,
help=help,
disabled=disabled,
required=required,
pinned=pinned,
default=None if default is None else default.isoformat(),
type_config=TimeColumnConfig(
type="time",
format=format,
min_value=None if min_value is None else min_value.isoformat(),
max_value=None if max_value is None else max_value.isoformat(),
step=step.total_seconds() if isinstance(step, datetime.timedelta) else step,
),
)
@gather_metrics("column_config.DateColumn")
def DateColumn(
label: str | None = None,
*,
width: ColumnWidth | None = None,
help: str | None = None,
disabled: bool | None = None,
required: bool | None = None,
pinned: bool | None = None,
default: datetime.date | None = None,
format: str | Literal["localized", "distance", "iso8601"] | None = None,
min_value: datetime.date | None = None,
max_value: datetime.date | None = None,
step: int | None = None,
) -> ColumnConfig:
"""Configure a date column in ``st.dataframe`` or ``st.data_editor``.
This is the default column type for date values. This command needs to be used in
the ``column_config`` parameter of ``st.dataframe`` or ``st.data_editor``. When used
with ``st.data_editor``, editing will be enabled with a date picker widget.
Parameters
----------
label : str or None
The label shown at the top of the column. If this is ``None``
(default), the column name is used.
width : "small", "medium", "large", int, or None
The display width of the column. If this is ``None`` (default), the
column will be sized to fit the cell contents. Otherwise, this can be
one of the following:
- ``"small"``: 75px wide
- ``"medium"``: 200px wide
- ``"large"``: 400px wide
- An integer specifying the width in pixels
If the total width of all columns is less than the width of the
dataframe, the remaining space will be distributed evenly among all
columns.
help : str or None
A tooltip that gets displayed when hovering over the column label. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown, including
the Markdown directives described in the ``body`` parameter of
``st.markdown``.
disabled : bool or None
Whether editing should be disabled for this column. If this is ``None``
(default), Streamlit will enable editing wherever possible.
If a column has mixed types, it may become uneditable regardless of
``disabled``.
required : bool or None
Whether edited cells in the column need to have a value. If this is
``False`` (default), the user can submit empty values for this column.
If this is ``True``, an edited cell in this column can only be
submitted if its value is not ``None``, and a new row will only be
submitted after the user fills in this column.
pinned : bool or None
Whether the column is pinned. A pinned column will stay visible on the
left side no matter where the user scrolls. If this is ``None``
(default), Streamlit will decide: index columns are pinned, and data
columns are not pinned.
default : datetime.date or None
Specifies the default value in this column when a new row is added by
the user. This defaults to ``None``.
format : str, "localized", "distance", "iso8601", or None
A format string controlling how dates are displayed.
This can be one of the following values:
- ``None`` (default): Show the date in ``"YYYY-MM-DD"`` format (e.g.
"2025-03-04").
- ``"localized"``: Show the date in the default locale format (e.g.
"Mar 4, 2025" in the America/Los_Angeles timezone).
- ``"distance"``: Show the date in a relative format (e.g.
"a few seconds ago").
- ``"iso8601"``: Show the date in ISO 8601 format (e.g.
"2025-03-04").
- A momentJS format string: Format the date with a string, like
``"ddd, MMM Do"`` to show "Tue, Mar 4th". For available formats, see
`momentJS <https://momentjs.com/docs/#/displaying/format/>`_.
Formatting from ``column_config`` always takes precedence over
formatting from ``pandas.Styler``. The formatting does not impact the
return value when used in ``st.data_editor``.
min_value : datetime.date or None
The minimum date that can be entered. If this is ``None`` (default),
there will be no minimum.
max_value : datetime.date or None
The maximum date that can be entered. If this is ``None`` (default),
there will be no maximum.
step : int or None
The stepping interval in days. If this is ``None`` (default), the step
will be 1 day.
Examples
--------
>>> from datetime import date
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> data_df = pd.DataFrame(
>>> {
>>> "birthday": [
>>> date(1980, 1, 1),
>>> date(1990, 5, 3),
>>> date(1974, 5, 19),
>>> date(2001, 8, 17),
>>> ]
>>> }
>>> )
>>>
>>> st.data_editor(
>>> data_df,
>>> column_config={
>>> "birthday": st.column_config.DateColumn(
>>> "Birthday",
>>> min_value=date(1900, 1, 1),
>>> max_value=date(2005, 1, 1),
>>> format="DD.MM.YYYY",
>>> step=1,
>>> ),
>>> },
>>> hide_index=True,
>>> )
.. output::
https://doc-date-column.streamlit.app/
height: 300px
"""
return ColumnConfig(
label=label,
width=width,
help=help,
disabled=disabled,
required=required,
pinned=pinned,
default=None if default is None else default.isoformat(),
type_config=DateColumnConfig(
type="date",
format=format,
min_value=None if min_value is None else min_value.isoformat(),
max_value=None if max_value is None else max_value.isoformat(),
step=step,
),
)
@gather_metrics("column_config.ProgressColumn")
def ProgressColumn(
label: str | None = None,
*,
width: ColumnWidth | None = None,
help: str | None = None,
pinned: bool | None = None,
format: str | NumberFormat | None = None,
min_value: int | float | None = None,
max_value: int | float | None = None,
step: int | float | None = None,
color: ChartColor | None = None,
) -> ColumnConfig:
"""Configure a progress column in ``st.dataframe`` or ``st.data_editor``.
Cells need to contain a number. Progress columns are not editable at the moment.
This command needs to be used in the ``column_config`` parameter of ``st.dataframe``
or ``st.data_editor``.
Parameters
----------
label : str or None
The label shown at the top of the column. If this is ``None``
(default), the column name is used.
width : "small", "medium", "large", int, or None
The display width of the column. If this is ``None`` (default), the
column will be sized to fit the cell contents. Otherwise, this can be
one of the following:
- ``"small"``: 75px wide
- ``"medium"``: 200px wide
- ``"large"``: 400px wide
- An integer specifying the width in pixels
If the total width of all columns is less than the width of the
dataframe, the remaining space will be distributed evenly among all
columns.
help : str or None
A tooltip that gets displayed when hovering over the column label. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown, including
the Markdown directives described in the ``body`` parameter of
``st.markdown``.
format : str, "plain", "localized", "percent", "dollar", "euro", "yen", "accounting", "compact", "scientific", "engineering", or None
A format string controlling how the numbers are displayed.
This can be one of the following values:
- ``None`` (default): Streamlit infers the formatting from the data.
- ``"plain"``: Show the full number without any formatting (e.g. "1234.567").
- ``"localized"``: Show the number in the default locale format (e.g. "1,234.567").
- ``"percent"``: Show the number as a percentage (e.g. "123456.70%").
- ``"dollar"``: Show the number as a dollar amount (e.g. "$1,234.57").
- ``"euro"``: Show the number as a euro amount (e.g. "€1,234.57").
- ``"yen"``: Show the number as a yen amount (e.g. "¥1,235").
- ``"accounting"``: Show the number in an accounting format (e.g. "1,234.00").
- ``"bytes"``: Show the number in a byte format (e.g. "1.2KB").
- ``"compact"``: Show the number in a compact format (e.g. "1.2K").
- ``"scientific"``: Show the number in scientific notation (e.g. "1.235E3").
- ``"engineering"``: Show the number in engineering notation (e.g. "1.235E3").
- printf-style format string: Format the number with a printf
specifier, like ``"%d"`` to show a signed integer (e.g. "1234") or
``"%X"`` to show an unsigned hexadecimal integer (e.g. "4D2"). You
can also add prefixes and suffixes. To show British pounds, use
``"£ %.2f"`` (e.g. "£ 1234.57"). For more information, see `sprint-js
<https://github.com/alexei/sprintf.js?tab=readme-ov-file#format-specification>`_.
Number formatting from ``column_config`` always takes precedence over
number formatting from ``pandas.Styler``. The number formatting does
not impact the return value when used in ``st.data_editor``.
pinned : bool or None
Whether the column is pinned. A pinned column will stay visible on the
left side no matter where the user scrolls. If this is ``None``
(default), Streamlit will decide: index columns are pinned, and data
columns are not pinned.
min_value : int, float, or None
The minimum value of the progress bar. If this is ``None`` (default),
the minimum will be 0.
max_value : int, float, or None
The maximum value of the progress bar. If this is ``None`` (default),
the maximum will be 100 for integer values and 1.0 for float values.
step : int, float, or None
The precision of numbers. If this is ``None`` (default), integer columns
will have a step of 1 and float columns will have a step of 0.01.
Setting ``step`` for float columns will ensure a consistent number of
digits after the decimal are displayed.
color : "auto", "auto-inverse", str, or None
The color to use for the chart. This can be one of the following:
- ``None`` (default): The primary color is used.
- ``"auto"``: If the value is more than half, the bar is green; if the
value is less than half, the bar is red.
- ``"auto-inverse"``: If the value is more than half, the bar is red;
if the value is less than half, the bar is green.
- A single color value that is applied to all charts in the column.
In addition to the basic color palette (red, orange, yellow, green,
blue, violet, gray/grey, and primary), this supports hex codes like
``"#483d8b"``.
Examples
--------
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> data_df = pd.DataFrame(
>>> {
>>> "sales": [200, 550, 1000, 80],
>>> }
>>> )
>>>
>>> st.data_editor(
>>> data_df,
>>> column_config={
>>> "sales": st.column_config.ProgressColumn(
>>> "Sales volume",
>>> help="The sales volume in USD",
>>> format="$%f",
>>> min_value=0,
>>> max_value=1000,
>>> ),
>>> },
>>> hide_index=True,
>>> )
.. output::
https://doc-progress-column.streamlit.app/
height: 300px
""" # noqa: E501
if color is not None:
_validate_chart_color(color)
return ColumnConfig(
label=label,
width=width,
help=help,
pinned=pinned,
type_config=ProgressColumnConfig(
type="progress",
format=format,
min_value=min_value,
max_value=max_value,
step=step,
color=color,
),
)
@gather_metrics("column_config.JsonColumn")
def JsonColumn(
label: str | None = None,
*,
width: ColumnWidth | None = None,
help: str | None = None,
pinned: bool | None = None,
) -> ColumnConfig:
"""Configure a JSON column in ``st.dataframe`` or ``st.data_editor``.
Cells need to contain JSON strings or JSON-compatible objects. JSON columns
are not editable at the moment. This command needs to be used in the
``column_config`` parameter of ``st.dataframe`` or ``st.data_editor``.
Parameters
----------
label : str or None
The label shown at the top of the column. If this is ``None``
(default), the column name is used.
width : "small", "medium", "large", int, or None
The display width of the column. If this is ``None`` (default), the
column will be sized to fit the cell contents. Otherwise, this can be
one of the following:
- ``"small"``: 75px wide
- ``"medium"``: 200px wide
- ``"large"``: 400px wide
- An integer specifying the width in pixels
If the total width of all columns is less than the width of the
dataframe, the remaining space will be distributed evenly among all
columns.
help : str or None
A tooltip that gets displayed when hovering over the column label. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown, including
the Markdown directives described in the ``body`` parameter of
``st.markdown``.
pinned : bool or None
Whether the column is pinned. A pinned column will stay visible on the
left side no matter where the user scrolls. If this is ``None``
(default), Streamlit will decide: index columns are pinned, and data
columns are not pinned.
Examples
--------
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> data_df = pd.DataFrame(
>>> {
>>> "json": [
>>> {"foo": "bar", "bar": "baz"},
>>> {"foo": "baz", "bar": "qux"},
>>> {"foo": "qux", "bar": "foo"},
>>> None,
>>> ],
>>> }
>>> )
>>>
>>> st.dataframe(
>>> data_df,
>>> column_config={
>>> "json": st.column_config.JsonColumn(
>>> "JSON Data",
>>> help="JSON strings or objects",
>>> width="large",
>>> ),
>>> },
>>> hide_index=True,
>>> )
.. output::
https://doc-json-column.streamlit.app/
height: 300px
"""
return ColumnConfig(
label=label,
width=width,
help=help,
pinned=pinned,
type_config=JsonColumnConfig(type="json"),
)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/lib/layout_utils.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from dataclasses import dataclass
from typing import Literal, TypeAlias, cast
from streamlit.errors import (
StreamlitInvalidColumnGapError,
StreamlitInvalidHeightError,
StreamlitInvalidHorizontalAlignmentError,
StreamlitInvalidSizeError,
StreamlitInvalidTextAlignmentError,
StreamlitInvalidVerticalAlignmentError,
StreamlitInvalidWidthError,
)
from streamlit.proto.Block_pb2 import Block
from streamlit.proto.GapSize_pb2 import GapSize
from streamlit.proto.HeightConfig_pb2 import HeightConfig
from streamlit.proto.TextAlignmentConfig_pb2 import TextAlignmentConfig
from streamlit.proto.WidthConfig_pb2 import WidthConfig
WidthWithoutContent: TypeAlias = int | Literal["stretch"]
Width: TypeAlias = int | Literal["stretch", "content"]
HeightWithoutContent: TypeAlias = int | Literal["stretch"]
Height: TypeAlias = int | Literal["stretch", "content"]
SpaceSize: TypeAlias = int | Literal["stretch", "small", "medium", "large"]
Gap: TypeAlias = Literal["small", "medium", "large"]
HorizontalAlignment: TypeAlias = Literal["left", "center", "right", "distribute"]
VerticalAlignment: TypeAlias = Literal["top", "center", "bottom", "distribute"]
TextAlignment: TypeAlias = Literal["left", "center", "right", "justify"]
# Mapping of size literals to rem values for st.space
# If changing these, also check streamlit/frontend/lib/src/theme/primitives/sizes.ts
# to ensure sizes are kept in sync.
SIZE_TO_REM_MAPPING = {
"small": 0.75, # Height of widget label minus gap
"medium": 2.5, # Height of button/input field
"large": 4.25, # Height of large widget without label
}
@dataclass
class LayoutConfig:
width: Width | SpaceSize | None = None
height: Height | SpaceSize | None = None
text_alignment: TextAlignment | None = None
def validate_width(width: Width, allow_content: bool = False) -> None:
"""Validate the width parameter.
Parameters
----------
width : Any
The width value to validate.
allow_content : bool
Whether to allow "content" as a valid width value.
Raises
------
StreamlitInvalidWidthError
If the width value is invalid.
"""
if not isinstance(width, (int, str)):
raise StreamlitInvalidWidthError(width, allow_content)
if isinstance(width, str):
valid_strings = ["stretch"]
if allow_content:
valid_strings.append("content")
if width not in valid_strings:
raise StreamlitInvalidWidthError(width, allow_content)
elif width <= 0:
raise StreamlitInvalidWidthError(width, allow_content)
def validate_height(
height: Height | Literal["auto"],
allow_content: bool = False,
allow_stretch: bool = True,
additional_allowed: list[str] | None = None,
) -> None:
"""Validate the height parameter.
Parameters
----------
height : Any
The height value to validate.
allow_content : bool
Whether to allow "content" as a valid height value.
allow_stretch : bool
Whether to allow "stretch" as a valid height value.
additional_allowed : list[str] or None
Additional string values to allow beyond the base allowed values.
Raises
------
StreamlitInvalidHeightError
If the height value is invalid.
"""
if not isinstance(height, (int, str)):
raise StreamlitInvalidHeightError(height, allow_content)
if isinstance(height, str):
valid_strings = []
if allow_stretch:
valid_strings.append("stretch")
if allow_content:
valid_strings.append("content")
if additional_allowed:
valid_strings.extend(additional_allowed)
if height not in valid_strings:
raise StreamlitInvalidHeightError(height, allow_content)
elif height <= 0:
raise StreamlitInvalidHeightError(height, allow_content)
def validate_space_size(size: SpaceSize) -> None:
"""Validate the size parameter for st.space.
Parameters
----------
size : Any
The size value to validate.
Raises
------
StreamlitInvalidSizeError
If the size value is invalid.
"""
if not isinstance(size, (int, str)):
raise StreamlitInvalidSizeError(size)
if isinstance(size, str):
valid_strings = ["stretch", "small", "medium", "large"]
if size not in valid_strings:
raise StreamlitInvalidSizeError(size)
elif isinstance(size, int) and size <= 0:
raise StreamlitInvalidSizeError(size)
def get_width_config(width: Width | SpaceSize) -> WidthConfig:
width_config = WidthConfig()
if isinstance(width, str) and width in SIZE_TO_REM_MAPPING:
width_config.rem_width = SIZE_TO_REM_MAPPING[width]
elif isinstance(width, (int, float)):
width_config.pixel_width = int(width)
elif width == "content":
width_config.use_content = True
else:
width_config.use_stretch = True
return width_config
def get_height_config(height: Height | SpaceSize) -> HeightConfig:
height_config = HeightConfig()
if isinstance(height, str) and height in SIZE_TO_REM_MAPPING:
height_config.rem_height = SIZE_TO_REM_MAPPING[height]
elif isinstance(height, (int, float)):
height_config.pixel_height = int(height)
elif height == "content":
height_config.use_content = True
else:
height_config.use_stretch = True
return height_config
def get_gap_size(gap: str | None, element_type: str) -> GapSize.ValueType:
"""Convert a gap string or None to a GapSize proto value."""
gap_mapping = {
"small": GapSize.SMALL,
"medium": GapSize.MEDIUM,
"large": GapSize.LARGE,
}
if isinstance(gap, str):
gap_size = gap.lower()
valid_sizes = gap_mapping.keys()
if gap_size in valid_sizes:
return gap_mapping[gap_size]
elif gap is None:
return GapSize.NONE
raise StreamlitInvalidColumnGapError(gap=gap, element_type=element_type)
def validate_horizontal_alignment(horizontal_alignment: HorizontalAlignment) -> None:
valid_horizontal_alignments = ["left", "center", "right", "distribute"]
if horizontal_alignment not in valid_horizontal_alignments:
raise StreamlitInvalidHorizontalAlignmentError(
horizontal_alignment, "st.container"
)
def validate_vertical_alignment(vertical_alignment: VerticalAlignment) -> None:
valid_vertical_alignments = ["top", "center", "bottom", "distribute"]
if vertical_alignment not in valid_vertical_alignments:
raise StreamlitInvalidVerticalAlignmentError(vertical_alignment, "st.container")
def validate_text_alignment(text_alignment: TextAlignment) -> None:
"""Validate the text_alignment parameter.
Parameters
----------
text_alignment : TextAlignment
The text alignment value to validate.
Raises
------
StreamlitInvalidTextAlignmentError
If the text_alignment value is invalid.
"""
valid_alignments = ["left", "center", "right", "justify"]
if text_alignment not in valid_alignments:
raise StreamlitInvalidTextAlignmentError(text_alignment)
map_to_flex_terminology = {
"left": "start",
"center": "center",
"right": "end",
"top": "start",
"bottom": "end",
"distribute": "space_between",
}
def get_justify(
alignment: HorizontalAlignment | VerticalAlignment,
) -> Block.FlexContainer.Justify.ValueType:
valid_justify = ["start", "center", "end", "space_between"]
justify = map_to_flex_terminology[alignment]
if justify not in valid_justify:
return Block.FlexContainer.Justify.JUSTIFY_UNDEFINED
if justify in ["start", "end", "center"]:
return cast(
"Block.FlexContainer.Justify.ValueType",
getattr(Block.FlexContainer.Justify, f"JUSTIFY_{justify.upper()}"),
)
return cast(
"Block.FlexContainer.Justify.ValueType",
getattr(Block.FlexContainer.Justify, f"{justify.upper()}"),
)
def get_align(
alignment: HorizontalAlignment | VerticalAlignment,
) -> Block.FlexContainer.Align.ValueType:
valid_align = ["start", "end", "center"]
align = map_to_flex_terminology[alignment]
if align not in valid_align:
return Block.FlexContainer.Align.ALIGN_UNDEFINED
return cast(
"Block.FlexContainer.Align.ValueType",
getattr(Block.FlexContainer.Align, f"ALIGN_{align.upper()}"),
)
def get_text_alignment_config(
text_alignment: TextAlignment,
) -> TextAlignmentConfig:
"""Convert text alignment string to proto config.
Parameters
----------
text_alignment : TextAlignment
The text alignment value ("left", "center", "right", "justify").
Returns
-------
TextAlignmentConfig
Proto message with alignment set.
"""
alignment_mapping = {
"left": TextAlignmentConfig.Alignment.LEFT,
"center": TextAlignmentConfig.Alignment.CENTER,
"right": TextAlignmentConfig.Alignment.RIGHT,
"justify": TextAlignmentConfig.Alignment.JUSTIFY,
}
config = TextAlignmentConfig()
config.alignment = alignment_mapping[text_alignment]
return config
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/lib/utils.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import hashlib
from datetime import date, datetime, time, timedelta
from typing import (
TYPE_CHECKING,
Any,
Literal,
TypeAlias,
Union,
overload,
)
from google.protobuf.message import Message
from streamlit import config
from streamlit.elements.lib.form_utils import current_form_id
from streamlit.errors import StreamlitDuplicateElementId, StreamlitDuplicateElementKey
from streamlit.proto.ChatInput_pb2 import ChatInput
from streamlit.proto.LabelVisibilityMessage_pb2 import LabelVisibilityMessage
from streamlit.runtime.scriptrunner_utils.script_run_context import (
ScriptRunContext,
get_script_run_ctx,
)
from streamlit.runtime.state.common import (
GENERATED_ELEMENT_ID_PREFIX,
TESTING_KEY,
user_key_from_element_id,
)
if TYPE_CHECKING:
from builtins import ellipsis
from collections.abc import Iterable
from streamlit.delta_generator import DeltaGenerator
Key: TypeAlias = str | int
LabelVisibility: TypeAlias = Literal["visible", "hidden", "collapsed"]
PROTO_SCALAR_VALUE: TypeAlias = float | int | bool | str | bytes
SAFE_VALUES: TypeAlias = Union[
date,
time,
datetime,
timedelta,
None,
"ellipsis",
Message,
PROTO_SCALAR_VALUE,
]
def get_label_visibility_proto_value(
label_visibility_string: LabelVisibility,
) -> LabelVisibilityMessage.LabelVisibilityOptions.ValueType:
"""Returns one of LabelVisibilityMessage enum constants.py based on string value."""
if label_visibility_string == "visible":
return LabelVisibilityMessage.LabelVisibilityOptions.VISIBLE
if label_visibility_string == "hidden":
return LabelVisibilityMessage.LabelVisibilityOptions.HIDDEN
if label_visibility_string == "collapsed":
return LabelVisibilityMessage.LabelVisibilityOptions.COLLAPSED
raise ValueError(f"Unknown label visibility value: {label_visibility_string}")
def get_chat_input_accept_file_proto_value(
accept_file_value: Literal["multiple", "directory"] | bool,
) -> ChatInput.AcceptFile.ValueType:
"""Returns one of ChatInput.AcceptFile enum value based on string value."""
if accept_file_value is False:
return ChatInput.AcceptFile.NONE
if accept_file_value is True:
return ChatInput.AcceptFile.SINGLE
if accept_file_value == "multiple":
return ChatInput.AcceptFile.MULTIPLE
if accept_file_value == "directory":
return ChatInput.AcceptFile.DIRECTORY
raise ValueError(f"Unknown accept file value: {accept_file_value}")
@overload
def to_key(key: None) -> None: ...
@overload
def to_key(key: Key) -> str: ...
def to_key(key: Key | None) -> str | None:
return None if key is None else str(key)
def _register_element_id(
ctx: ScriptRunContext, element_type: str, element_id: str
) -> None:
"""Register the element ID and key for the given element.
If the element ID or key is not unique, an error is raised.
Parameters
----------
element_type : str
The type of the element to register.
element_id : str
The ID of the element to register.
Raises
------
StreamlitDuplicateElementKey
If the element key is not unique.
StreamlitDuplicateElementID
If the element ID is not unique.
"""
if not element_id:
return
if user_key := user_key_from_element_id(element_id):
if user_key not in ctx.widget_user_keys_this_run:
ctx.widget_user_keys_this_run.add(user_key)
else:
raise StreamlitDuplicateElementKey(user_key)
if element_id not in ctx.widget_ids_this_run:
ctx.widget_ids_this_run.add(element_id)
else:
raise StreamlitDuplicateElementId(element_type)
def _compute_element_id(
element_type: str,
user_key: str | None = None,
**kwargs: SAFE_VALUES | Iterable[SAFE_VALUES],
) -> str:
"""Compute the ID for the given element.
This ID is stable: a given set of inputs to this function will always produce
the same ID output. Only stable, deterministic values should be used to compute
element IDs. Using nondeterministic values as inputs can cause the resulting
element ID to change between runs.
The element ID includes the user_key so elements with identical arguments can
use it to be distinct. The element ID includes an easily identified prefix, and the
user_key as a suffix, to make it easy to identify it and know if a key maps to it.
"""
h = hashlib.new("md5", usedforsecurity=False)
h.update(element_type.encode("utf-8"))
if user_key:
# Adding this to the hash isn't necessary for uniqueness since the
# key is also appended to the ID as raw text. But since the hash and
# the appending of the key are two slightly different aspects, it
# still gets put into the hash.
h.update(user_key.encode("utf-8"))
# This will iterate in a consistent order when the provided arguments have
# consistent order; dicts are always in insertion order.
for k, v in kwargs.items():
h.update(str(k).encode("utf-8"))
h.update(str(v).encode("utf-8"))
return f"{GENERATED_ELEMENT_ID_PREFIX}-{h.hexdigest()}-{user_key}"
def compute_and_register_element_id(
element_type: str,
*,
user_key: str | None,
dg: DeltaGenerator | None,
key_as_main_identity: bool | set[str],
**kwargs: SAFE_VALUES | Iterable[SAFE_VALUES],
) -> str:
"""Compute and register the ID for the given element.
This ID is stable: a given set of inputs to this function will always produce
the same ID output. Only stable, deterministic values should be used to compute
element IDs. Using nondeterministic values as inputs can cause the resulting
element ID to change between runs.
The element ID includes the user_key so elements with identical arguments can
use it to be distinct. The element ID includes an easily identified prefix, and the
user_key as a suffix, to make it easy to identify it and know if a key maps to it.
The element ID gets registered to make sure that only one ID and user-specified
key exists at the same time. If there are duplicated IDs or keys, an error
is raised.
Parameters
----------
element_type : str
The type (command name) of the element to register.
user_key : str | None
The user-specified key for the element. `None` if no key is provided
or if the element doesn't support a specifying a key.
dg : DeltaGenerator | None
The DeltaGenerator of each element. `None` if the element is not a widget.
kwargs : SAFE_VALUES | Iterable[SAFE_VALUES]
The arguments to use to compute the element ID.
The arguments must be stable, deterministic values.
Some common parameters like key, disabled,
format_func, label_visibility, args, kwargs, on_change, and
the active_script_hash are not supposed to be added here
key_as_main_identity : bool | set[str]
If True and a key is provided by the user, we don't include
command kwargs in the element ID computation.
If a set of kwarg names is provided and a key is provided,
only the kwargs with names in this set will be included
in the element ID computation.
"""
ctx = get_script_run_ctx()
# When a user_key is present and key_as_main_identity is True OR a set (even empty),
# we should ignore general command kwargs and form/sidebar context. For the set case,
# only explicitly whitelisted kwargs will be included below.
ignore_command_kwargs = user_key is not None and (
(key_as_main_identity is True) or isinstance(key_as_main_identity, set)
)
if isinstance(key_as_main_identity, set) and user_key:
# Only include the explicitly whitelisted kwargs in the computation
kwargs_to_use = {k: v for k, v in kwargs.items() if k in key_as_main_identity}
else:
kwargs_to_use = {} if ignore_command_kwargs else {**kwargs}
if ctx:
# Add the active script hash to give elements on different
# pages unique IDs. This is added even if
# key_as_main_identity is specified.
kwargs_to_use["active_script_hash"] = ctx.active_script_hash
if dg and not ignore_command_kwargs:
kwargs_to_use["form_id"] = current_form_id(dg)
# If no key is provided and the widget element is inside the sidebar area
# add it to the kwargs
# allowing the same widget to be both in main area and sidebar.
kwargs_to_use["active_dg_root_container"] = dg._active_dg._root_container
element_id = _compute_element_id(element_type, user_key, **kwargs_to_use)
if ctx:
_register_element_id(ctx, element_type, element_id)
return element_id
def save_for_app_testing(ctx: ScriptRunContext, k: str, v: Any) -> None:
if config.get_option("global.appTest"):
try:
ctx.session_state[TESTING_KEY][k] = v
except KeyError:
ctx.session_state[TESTING_KEY] = {k: v}
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/lib/pandas_styler_utils.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from collections import defaultdict
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar
from streamlit import dataframe_util
from streamlit.errors import StreamlitAPIException
if TYPE_CHECKING:
from pandas import DataFrame
from pandas.io.formats.style import Styler
from streamlit.proto.Arrow_pb2 import Arrow as ArrowProto
from enum import Enum
def marshall_styler(proto: ArrowProto, styler: Styler, default_uuid: str) -> None:
"""Marshall pandas.Styler into an Arrow proto.
Parameters
----------
proto : proto.Arrow
Output. The protobuf for Streamlit Arrow proto.
styler : pandas.Styler
Helps style a DataFrame or Series according to the data with HTML and CSS.
default_uuid : str
If pandas.Styler uuid is not provided, this value will be used.
"""
import pandas as pd
styler_data_df: pd.DataFrame = styler.data # type: ignore[attr-defined]
if styler_data_df.size > int(pd.options.styler.render.max_elements):
raise StreamlitAPIException(
f"The dataframe has `{styler_data_df.size}` cells, but the maximum number "
"of cells allowed to be rendered by Pandas Styler is configured to "
f"`{pd.options.styler.render.max_elements}`. To allow more cells to be "
'styled, you can change the `"styler.render.max_elements"` config. For example: '
f'`pd.set_option("styler.render.max_elements", {styler_data_df.size})`'
)
# pandas.Styler uuid should be set before _compute is called.
_marshall_uuid(proto, styler, default_uuid)
# We're using protected members of pandas.Styler to get styles,
# which is not ideal and could break if the interface changes.
styler._compute() # type: ignore
pandas_styles = styler._translate(False, False) # type: ignore
_marshall_caption(proto, styler)
_marshall_styles(proto, styler, pandas_styles)
_marshall_display_values(proto, styler_data_df, pandas_styles)
def _marshall_uuid(proto: ArrowProto, styler: Styler, default_uuid: str) -> None:
"""Marshall pandas.Styler uuid into an Arrow proto.
Parameters
----------
proto : proto.Arrow
Output. The protobuf for Streamlit Arrow proto.
styler : pandas.Styler
Helps style a DataFrame or Series according to the data with HTML and CSS.
default_uuid : str
If pandas.Styler uuid is not provided, this value will be used.
"""
if styler.uuid is None: # type: ignore[attr-defined]
styler.set_uuid(default_uuid)
proto.styler.uuid = str(styler.uuid) # type: ignore[attr-defined]
def _marshall_caption(proto: ArrowProto, styler: Styler) -> None:
"""Marshall pandas.Styler caption into an Arrow proto.
Parameters
----------
proto : proto.Arrow
Output. The protobuf for Streamlit Arrow proto.
styler : pandas.Styler
Helps style a DataFrame or Series according to the data with HTML and CSS.
"""
if styler.caption is not None: # type: ignore[attr-defined]
proto.styler.caption = styler.caption # type: ignore[attr-defined]
def _marshall_styles(
proto: ArrowProto, styler: Styler, styles: Mapping[str, Any]
) -> None:
"""Marshall pandas.Styler styles into an Arrow proto.
Parameters
----------
proto : proto.Arrow
Output. The protobuf for Streamlit Arrow proto.
styler : pandas.Styler
Helps style a DataFrame or Series according to the data with HTML and CSS.
styles : dict
pandas.Styler translated styles.
"""
css_rules = []
if "table_styles" in styles:
table_styles = styles["table_styles"]
table_styles = _trim_pandas_styles(table_styles)
for style in table_styles:
# styles in "table_styles" have a space
# between the uuid and selector.
rule = _pandas_style_to_css(
"table_styles",
style,
styler.uuid, # type: ignore[attr-defined]
separator=" ",
)
css_rules.append(rule)
if "cellstyle" in styles:
cellstyle = styles["cellstyle"]
cellstyle = _trim_pandas_styles(cellstyle)
for style in cellstyle:
rule = _pandas_style_to_css(
"cell_style",
style,
styler.uuid, # type: ignore[attr-defined]
separator="_",
)
css_rules.append(rule)
if len(css_rules) > 0:
proto.styler.styles = "\n".join(css_rules)
M = TypeVar("M", bound=Mapping[str, Any])
def _trim_pandas_styles(styles: list[M]) -> list[M]:
"""Filter out empty styles.
Every cell will have a class, but the list of props
may just be [['', '']].
Parameters
----------
styles : list
pandas.Styler translated styles.
"""
return [x for x in styles if any(any(y) for y in x["props"])]
def _pandas_style_to_css(
style_type: str,
style: Mapping[str, Any],
uuid: str,
separator: str = "_",
) -> str:
"""Convert pandas.Styler translated style to CSS.
Parameters
----------
style_type : str
Either "table_styles" or "cell_style".
style : dict
pandas.Styler translated style.
uuid : str
pandas.Styler uuid.
separator : str
A string separator used between table and cell selectors.
"""
declarations = []
for css_property, css_value in style["props"]:
declaration = str(css_property).strip() + ": " + str(css_value).strip()
declarations.append(declaration)
table_selector = f"#T_{uuid}"
# In pandas >= 1.1.0
# translated_style["cellstyle"] has the following shape:
# > [
# > {
# > "props": [("color", " black"), ("background-color", "orange"), ("", "")],
# > "selectors": ["row0_col0"]
# > }
# > ...
# > ]
cell_selectors = (
[style["selector"]] if style_type == "table_styles" else style["selectors"]
)
selectors = [
table_selector + separator + cell_selector for cell_selector in cell_selectors
]
selector = ", ".join(selectors)
declaration_block = "; ".join(declarations)
return selector + " { " + declaration_block + " }"
def _marshall_display_values(
proto: ArrowProto, df: DataFrame, styles: Mapping[str, Any]
) -> None:
"""Marshall pandas.Styler display values into an Arrow proto.
Parameters
----------
proto : proto.Arrow
Output. The protobuf for Streamlit Arrow proto.
df : pandas.DataFrame
A dataframe with original values.
styles : dict
pandas.Styler translated styles.
"""
new_df = _use_display_values(df, styles)
proto.styler.display_values = dataframe_util.convert_pandas_df_to_arrow_bytes(
new_df
)
def _use_display_values(df: DataFrame, styles: Mapping[str, Any]) -> DataFrame:
"""Create a new pandas.DataFrame where display values are used instead of original ones.
Parameters
----------
df : pandas.DataFrame
A dataframe with original values.
styles : dict
pandas.Styler translated styles.
"""
import re
# If values in a column are not of the same type, Arrow
# serialization would fail. Thus, we need to cast all values
# of the dataframe to strings before assigning them display values.
new_df = df.astype(str)
cell_selector_regex = re.compile(r"row(\d+)_col(\d+)")
# Outer key = column index; inner key = row index -> target string value
updates_by_col: defaultdict[int, dict[int, str]] = defaultdict(dict)
for row in styles.get("body", []):
for cell in row:
cell_id = cell.get("id")
if not cell_id:
continue
match = cell_selector_regex.match(cell_id)
if not match:
continue
row_idx, col_idx = map(int, match.groups())
display_value = cell.get("display_value")
str_value = (
str(display_value.value)
# Check if the display value is an Enum type. Enum values need to be
# converted to their `.value` attribute to ensure proper serialization
# and display logic.
if isinstance(display_value, Enum)
else str(display_value)
)
updates_by_col[col_idx][row_idx] = str_value
for col_idx, values_by_row in updates_by_col.items():
row_indices = list(values_by_row.keys())
values = list(values_by_row.values())
# Batch-assign updates for this column using iloc for performance.
new_df.iloc[row_indices, col_idx] = values
return new_df
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/widgets/file_uploader.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from dataclasses import dataclass
from textwrap import dedent
from typing import TYPE_CHECKING, Literal, TypeAlias, cast, overload
from streamlit import config
from streamlit.elements.lib.file_uploader_utils import (
enforce_filename_restriction,
normalize_upload_file_type,
)
from streamlit.elements.lib.form_utils import current_form_id
from streamlit.elements.lib.layout_utils import (
LayoutConfig,
WidthWithoutContent,
validate_width,
)
from streamlit.elements.lib.policies import (
check_widget_policies,
maybe_raise_label_warnings,
)
from streamlit.elements.lib.utils import (
Key,
LabelVisibility,
compute_and_register_element_id,
get_label_visibility_proto_value,
to_key,
)
from streamlit.proto.Common_pb2 import FileUploaderState as FileUploaderStateProto
from streamlit.proto.Common_pb2 import UploadedFileInfo as UploadedFileInfoProto
from streamlit.proto.FileUploader_pb2 import FileUploader as FileUploaderProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner import ScriptRunContext, get_script_run_ctx
from streamlit.runtime.state import (
WidgetArgs,
WidgetCallback,
WidgetKwargs,
register_widget,
)
from streamlit.runtime.uploaded_file_manager import DeletedFile, UploadedFile
if TYPE_CHECKING:
from collections.abc import Sequence
from streamlit.delta_generator import DeltaGenerator
SomeUploadedFiles: TypeAlias = (
UploadedFile | DeletedFile | list[UploadedFile | DeletedFile] | None
)
# Type alias for accept_multiple_files parameter.
# If True, multiple files can be uploaded.
# If False, only a single file can be uploaded.
# If set to the literal "directory", users can upload an entire directory (folder) of files.
AcceptMultipleFiles: TypeAlias = bool | Literal["directory"]
def _get_upload_files(
widget_value: FileUploaderStateProto | None,
) -> list[UploadedFile | DeletedFile]:
if widget_value is None:
return []
ctx = get_script_run_ctx()
if ctx is None:
return []
uploaded_file_info = widget_value.uploaded_file_info
if len(uploaded_file_info) == 0:
return []
file_recs_list = ctx.uploaded_file_mgr.get_files(
session_id=ctx.session_id,
file_ids=[f.file_id for f in uploaded_file_info],
)
file_recs = {f.file_id: f for f in file_recs_list}
collected_files: list[UploadedFile | DeletedFile] = []
for f in uploaded_file_info:
maybe_file_rec = file_recs.get(f.file_id)
if maybe_file_rec is not None:
uploaded_file = UploadedFile(maybe_file_rec, f.file_urls)
collected_files.append(uploaded_file)
else:
collected_files.append(DeletedFile(f.file_id))
return collected_files
@dataclass
class FileUploaderSerde:
accept_multiple_files: AcceptMultipleFiles
allowed_types: Sequence[str] | None = None
def deserialize(self, ui_value: FileUploaderStateProto | None) -> SomeUploadedFiles:
upload_files = _get_upload_files(ui_value)
for file in upload_files:
if isinstance(file, DeletedFile):
continue
if self.allowed_types:
enforce_filename_restriction(file.name, self.allowed_types)
# Directory uploads always return a list, similar to multiple files
is_multiple_or_directory = (
self.accept_multiple_files is True
or self.accept_multiple_files == "directory"
)
if len(upload_files) == 0:
return_value: SomeUploadedFiles = [] if is_multiple_or_directory else None
else:
return_value = upload_files if is_multiple_or_directory else upload_files[0]
return return_value
def serialize(self, files: SomeUploadedFiles) -> FileUploaderStateProto:
state_proto = FileUploaderStateProto()
if not files:
return state_proto
if not isinstance(files, list):
files = [files]
for f in files:
if isinstance(f, DeletedFile):
continue
file_info: UploadedFileInfoProto = state_proto.uploaded_file_info.add()
file_info.file_id = f.file_id
file_info.name = f.name
file_info.size = f.size
file_info.file_urls.CopyFrom(f._file_urls)
return state_proto
class FileUploaderMixin:
# Multiple overloads are defined on `file_uploader()` below to represent
# the different return types of `file_uploader()`.
# These return types differ according to the value of the `accept_multiple_files` argument.
# There must be 2x2=4 overloads to cover all the possible arguments,
# as these overloads must be mutually exclusive for mypy.
# There are 3 associated variables, each with 2+ options.
# 1. The `accept_multiple_files` argument is set as `True` or `"directory"`,
# or it is set as `False` or omitted, in which case the default value `False`.
# 2. The `type` argument may or may not be provided as a keyword-only argument.
# 3. Directory uploads always return a list of UploadedFile objects.
# 1. type is given as not a keyword-only argument
# 2. accept_multiple_files = True or "directory"
@overload
def file_uploader(
self,
label: str,
type: str | Sequence[str] | None,
accept_multiple_files: Literal[True, "directory"],
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> list[UploadedFile]: ...
# 1. type is given as not a keyword-only argument
# 2. accept_multiple_files = False or omitted
@overload
def file_uploader(
self,
label: str,
type: str | Sequence[str] | None,
accept_multiple_files: Literal[False] = False,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> UploadedFile | None: ...
# The following 2 overloads represent the cases where
# the `type` argument is a keyword-only argument.
# See https://github.com/python/mypy/issues/4020#issuecomment-737600893
# for the related discussions and examples.
# 1. type is skipped or a keyword argument
# 2. accept_multiple_files = True or "directory"
@overload
def file_uploader(
self,
label: str,
*,
accept_multiple_files: Literal[True, "directory"],
type: str | Sequence[str] | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> list[UploadedFile]: ...
# 1. type is skipped or a keyword argument
# 2. accept_multiple_files = False or omitted
@overload
def file_uploader(
self,
label: str,
*,
accept_multiple_files: Literal[False] = False,
type: str | Sequence[str] | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> UploadedFile | None: ...
@gather_metrics("file_uploader")
def file_uploader(
self,
label: str,
type: str | Sequence[str] | None = None,
accept_multiple_files: AcceptMultipleFiles = False,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> UploadedFile | list[UploadedFile] | None:
r"""Display a file uploader widget.
By default, uploaded files are limited to 200 MB each. You can
configure this using the ``server.maxUploadSize`` config option. For
more information on how to set config options, see |config.toml|_.
.. |config.toml| replace:: ``config.toml``
.. _config.toml: https://docs.streamlit.io/develop/api-reference/configuration/config.toml
Parameters
----------
label : str
A short label explaining to the user what this file uploader is for.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
For accessibility reasons, you should never set an empty label, but
you can hide it with ``label_visibility`` if needed. In the future,
we may disallow empty labels by raising an exception.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
type : str, list of str, or None
The allowed file extension(s) for uploaded files. This can be one
of the following types:
- ``None`` (default): All file extensions are allowed.
- A string: A single file extension is allowed. For example, to
only accept CSV files, use ``"csv"``.
- A sequence of strings: Multiple file extensions are allowed. For
example, to only accept JPG/JPEG and PNG files, use
``["jpg", "jpeg", "png"]``.
.. note::
This is a best-effort check, but doesn't provide a
security guarantee against users uploading files of other types
or type extensions. The correct handling of uploaded files is
part of the app developer's responsibility.
accept_multiple_files : bool or "directory"
Whether to accept more than one file in a submission. This can be one
of the following values:
- ``False`` (default): The user can only submit one file at a time.
- ``True``: The user can upload multiple files at the same time.
- ``"directory"``: The user can select a directory to upload all
files in the directory and its subdirectories. If ``type`` is
set, only files matching those type(s) will be uploaded.
When this is ``True`` or ``"directory"``, the return value will be
a list and a user can additively select files if they click the
browse button on the widget multiple times.
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. No two widgets may have the same key.
help : str or None
A tooltip that gets displayed next to the widget label. Streamlit
only displays the tooltip when ``label_visibility="visible"``. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
on_change : callable
An optional callback invoked when this file_uploader's value
changes.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
disabled : bool
An optional boolean that disables the file uploader if set to
``True``. The default is ``False``.
label_visibility : "visible", "hidden", or "collapsed"
The visibility of the label. The default is ``"visible"``. If this
is ``"hidden"``, Streamlit displays an empty spacer instead of the
label, which can help keep the widget aligned with other widgets.
If this is ``"collapsed"``, Streamlit displays no label or spacer.
width : "stretch" or int
The width of the file uploader widget. This can be one of the
following:
- ``"stretch"`` (default): The width of the widget matches the
width of the parent container.
- An integer specifying the width in pixels: The widget has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the widget matches the width
of the parent container.
Returns
-------
None, UploadedFile, or list of UploadedFile
- If accept_multiple_files is ``False``, returns either ``None`` or
an ``UploadedFile`` object.
- If accept_multiple_files is ``True`` or ``"directory"``, returns
a list with the uploaded files as ``UploadedFile`` objects. If no
files were uploaded, returns an empty list.
The ``UploadedFile`` class is a subclass of ``BytesIO``, and
therefore is "file-like". This means you can pass an instance of it
anywhere a file is expected.
Examples
--------
**Example 1: Accept a single file at a time**
>>> import streamlit as st
>>> import pandas as pd
>>> from io import StringIO
>>>
>>> uploaded_file = st.file_uploader("Choose a file")
>>> if uploaded_file is not None:
... # To read file as bytes:
... bytes_data = uploaded_file.getvalue()
... st.write(bytes_data)
>>>
... # To convert to a string based IO:
... stringio = StringIO(uploaded_file.getvalue().decode("utf-8"))
... st.write(stringio)
>>>
... # To read file as string:
... string_data = stringio.read()
... st.write(string_data)
>>>
... # Can be used wherever a "file-like" object is accepted:
... dataframe = pd.read_csv(uploaded_file)
... st.write(dataframe)
**Example 2: Accept multiple files at a time**
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> uploaded_files = st.file_uploader(
... "Upload data", accept_multiple_files=True, type="csv"
... )
>>> for uploaded_file in uploaded_files:
... df = pd.read_csv(uploaded_file)
... st.write(df)
.. output::
https://doc-file-uploader.streamlit.app/
height: 375px
**Example 3: Accept an entire directory**
>>> import streamlit as st
>>>
>>> uploaded_files = st.file_uploader(
... "Upload images", accept_multiple_files="directory", type=["jpg", "png"]
... )
>>> for uploaded_file in uploaded_files:
... st.image(uploaded_file)
.. output::
https://doc-file-uploader-directory.streamlit.app/
height: 375px
"""
ctx = get_script_run_ctx()
return self._file_uploader(
label=label,
type=type,
accept_multiple_files=accept_multiple_files,
key=key,
help=help,
on_change=on_change,
args=args,
kwargs=kwargs,
disabled=disabled,
label_visibility=label_visibility,
width=width,
ctx=ctx,
)
def _file_uploader(
self,
label: str,
type: str | Sequence[str] | None = None,
accept_multiple_files: AcceptMultipleFiles = False,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
label_visibility: LabelVisibility = "visible",
disabled: bool = False,
ctx: ScriptRunContext | None = None,
width: WidthWithoutContent = "stretch",
) -> UploadedFile | list[UploadedFile] | None:
key = to_key(key)
check_widget_policies(
self.dg,
key,
on_change,
default_value=None,
writes_allowed=False,
)
maybe_raise_label_warnings(label, label_visibility)
element_id = compute_and_register_element_id(
"file_uploader",
user_key=key,
# Treat the provided key as the main identity; only include
# changes to the type and accept_multiple_files parameters in
# the identity computation as those can invalidate the current value.
key_as_main_identity={"type", "accept_multiple_files"},
dg=self.dg,
label=label,
type=type,
accept_multiple_files=accept_multiple_files,
help=help,
width=width,
)
normalized_type = normalize_upload_file_type(type) if type else None
file_uploader_proto = FileUploaderProto()
file_uploader_proto.id = element_id
file_uploader_proto.label = label
file_uploader_proto.type[:] = (
normalized_type if normalized_type is not None else []
)
file_uploader_proto.max_upload_size_mb = config.get_option(
"server.maxUploadSize"
)
# Handle directory uploads - they should enable multiple files and set the directory flag
is_directory_upload = accept_multiple_files == "directory"
file_uploader_proto.multiple_files = (
accept_multiple_files is True or is_directory_upload
)
file_uploader_proto.accept_directory = is_directory_upload
file_uploader_proto.form_id = current_form_id(self.dg)
file_uploader_proto.disabled = disabled
file_uploader_proto.label_visibility.value = get_label_visibility_proto_value(
label_visibility
)
if help is not None:
file_uploader_proto.help = dedent(help)
serde = FileUploaderSerde(accept_multiple_files, allowed_types=normalized_type)
# FileUploader's widget value is a list of file IDs
# representing the current set of files that this uploader should
# know about.
widget_state = register_widget(
file_uploader_proto.id,
on_change_handler=on_change,
args=args,
kwargs=kwargs,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="file_uploader_state_value",
)
validate_width(width)
layout_config = LayoutConfig(width=width)
self.dg._enqueue(
"file_uploader", file_uploader_proto, layout_config=layout_config
)
if isinstance(widget_state.value, DeletedFile):
return None
if isinstance(widget_state.value, list):
return [f for f in widget_state.value if not isinstance(f, DeletedFile)]
return widget_state.value
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/widgets/__init__.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/widgets/select_slider.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from dataclasses import dataclass
from textwrap import dedent
from typing import (
TYPE_CHECKING,
Any,
Generic,
TypeGuard,
TypeVar,
cast,
overload,
)
from streamlit.dataframe_util import OptionSequence, convert_anything_to_list
from streamlit.elements.lib.form_utils import current_form_id
from streamlit.elements.lib.layout_utils import LayoutConfig, validate_width
from streamlit.elements.lib.options_selector_utils import (
index_,
maybe_coerce_enum,
maybe_coerce_enum_sequence,
)
from streamlit.elements.lib.policies import (
check_widget_policies,
maybe_raise_label_warnings,
)
from streamlit.elements.lib.utils import (
Key,
LabelVisibility,
compute_and_register_element_id,
get_label_visibility_proto_value,
save_for_app_testing,
to_key,
)
from streamlit.errors import StreamlitAPIException
from streamlit.proto.Slider_pb2 import Slider as SliderProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner import ScriptRunContext, get_script_run_ctx
from streamlit.runtime.state import (
WidgetArgs,
WidgetCallback,
WidgetKwargs,
register_widget,
)
from streamlit.type_util import check_python_comparable
if TYPE_CHECKING:
from collections.abc import Callable, Sequence
from streamlit.delta_generator import DeltaGenerator
from streamlit.elements.lib.layout_utils import WidthWithoutContent
from streamlit.runtime.state.common import RegisterWidgetResult
T = TypeVar("T")
def _is_range_value(value: T | Sequence[T]) -> TypeGuard[Sequence[T]]:
return isinstance(value, (list, tuple))
@dataclass
class SelectSliderSerde(Generic[T]):
options: Sequence[T]
value: list[int]
is_range_value: bool
def serialize(self, v: object) -> list[int]:
return self._as_index_list(v)
def deserialize(self, ui_value: list[int] | None) -> T | tuple[T, T]:
if not ui_value:
# Widget has not been used; fallback to the original value,
ui_value = self.value
# The widget always returns floats, so convert to ints before indexing
return_value: tuple[T, T] = cast(
"tuple[T, T]",
tuple(self.options[int(x)] for x in ui_value),
)
# If the original value was a list/tuple, so will be the output (and vice versa)
return return_value if self.is_range_value else return_value[0]
def _as_index_list(self, v: Any) -> list[int]:
if _is_range_value(v):
slider_value = [index_(self.options, val) for val in v]
start, end = slider_value
if start > end:
slider_value = [end, start]
return slider_value
return [index_(self.options, v)]
class SelectSliderMixin:
@overload
def select_slider(
self,
label: str,
options: OptionSequence[T],
value: tuple[T, T] | list[T],
format_func: Callable[[Any], Any] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> tuple[T, T]: ...
@overload
def select_slider(
self,
label: str,
options: OptionSequence[T] = (),
value: T | None = None,
format_func: Callable[[Any], Any] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> T: ...
@gather_metrics("select_slider")
def select_slider(
self,
label: str,
options: OptionSequence[T] = (),
value: T | Sequence[T] | None = None,
format_func: Callable[[Any], Any] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> T | tuple[T, T]:
r"""
Display a slider widget to select items from a list.
This also allows you to render a range slider by passing a two-element
tuple or list as the ``value``.
The difference between ``st.select_slider`` and ``st.slider`` is that
``select_slider`` accepts any datatype and takes an iterable set of
options, while ``st.slider`` only accepts numerical or date/time data and
takes a range as input.
Parameters
----------
label : str
A short label explaining to the user what this slider is for.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
For accessibility reasons, you should never set an empty label, but
you can hide it with ``label_visibility`` if needed. In the future,
we may disallow empty labels by raising an exception.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
options : Iterable
Labels for the select options in an ``Iterable``. This can be a
``list``, ``set``, or anything supported by ``st.dataframe``. If
``options`` is dataframe-like, the first column will be used. Each
label will be cast to ``str`` internally by default.
value : a supported type or a tuple/list of supported types or None
The value of the slider when it first renders. If a tuple/list
of two values is passed here, then a range slider with those lower
and upper bounds is rendered. For example, if set to `(1, 10)` the
slider will have a selectable range between 1 and 10.
Defaults to first option.
format_func : function
Function to modify the display of the labels from the options.
argument. It receives the option as an argument and its output
will be cast to str.
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. No two widgets may have the same key.
help : str or None
A tooltip that gets displayed next to the widget label. Streamlit
only displays the tooltip when ``label_visibility="visible"``. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
on_change : callable
An optional callback invoked when this select_slider's value changes.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
disabled : bool
An optional boolean that disables the select slider if set to
``True``. The default is ``False``.
label_visibility : "visible", "hidden", or "collapsed"
The visibility of the label. The default is ``"visible"``. If this
is ``"hidden"``, Streamlit displays an empty spacer instead of the
label, which can help keep the widget aligned with other widgets.
If this is ``"collapsed"``, Streamlit displays no label or spacer.
width : "stretch" or int
The width of the slider widget. This can be one of the
following:
- ``"stretch"`` (default): The width of the widget matches the
width of the parent container.
- An integer specifying the width in pixels: The widget has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the widget matches the width
of the parent container.
Returns
-------
any value or tuple of any value
The current value of the slider widget. The return type will match
the data type of the value parameter.
This contains copies of the selected options, not the originals.
Examples
--------
>>> import streamlit as st
>>>
>>> color = st.select_slider(
... "Select a color of the rainbow",
... options=[
... "red",
... "orange",
... "yellow",
... "green",
... "blue",
... "indigo",
... "violet",
... ],
... )
>>> st.write("My favorite color is", color)
And here's an example of a range select slider:
>>> import streamlit as st
>>>
>>> start_color, end_color = st.select_slider(
... "Select a range of color wavelength",
... options=[
... "red",
... "orange",
... "yellow",
... "green",
... "blue",
... "indigo",
... "violet",
... ],
... value=("red", "blue"),
... )
>>> st.write("You selected wavelengths between", start_color, "and", end_color)
.. output::
https://doc-select-slider.streamlit.app/
height: 450px
"""
ctx = get_script_run_ctx()
return self._select_slider(
label=label,
options=options,
value=value,
format_func=format_func,
key=key,
help=help,
on_change=on_change,
args=args,
kwargs=kwargs,
disabled=disabled,
label_visibility=label_visibility,
ctx=ctx,
width=width,
)
def _select_slider(
self,
label: str,
options: OptionSequence[T] = (),
value: T | Sequence[T] | None = None,
format_func: Callable[[Any], Any] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
ctx: ScriptRunContext | None = None,
width: WidthWithoutContent = "stretch",
) -> T | tuple[T, T]:
key = to_key(key)
check_widget_policies(
self.dg,
key,
on_change,
default_value=value,
)
maybe_raise_label_warnings(label, label_visibility)
opt = convert_anything_to_list(options)
check_python_comparable(opt)
if len(opt) == 0:
raise StreamlitAPIException("The `options` argument needs to be non-empty")
def as_index_list(v: Any) -> list[int]:
if _is_range_value(v):
slider_value = [index_(opt, val) for val in v]
start, end = slider_value
if start > end:
slider_value = [end, start]
return slider_value
# Simplify future logic by always making value a list
try:
return [index_(opt, v)]
except ValueError:
if value is not None:
raise
return [0]
# Convert element to index of the elements
slider_value = as_index_list(value)
element_id = compute_and_register_element_id(
"select_slider",
user_key=key,
# Treat the provided key as the main identity; only include
# changes to the options (and implicitly their formatting) in the
# identity computation as those can invalidate the current value.
key_as_main_identity={"options", "format_func"},
dg=self.dg,
label=label,
options=[str(format_func(option)) for option in opt],
value=slider_value,
help=help,
width=width,
)
slider_proto = SliderProto()
slider_proto.id = element_id
slider_proto.type = SliderProto.Type.SELECT_SLIDER
slider_proto.label = label
slider_proto.format = "%s"
slider_proto.default[:] = slider_value
slider_proto.min = 0
slider_proto.max = len(opt) - 1
slider_proto.step = 1 # default for index changes
slider_proto.data_type = SliderProto.INT
slider_proto.options[:] = [str(format_func(option)) for option in opt]
slider_proto.form_id = current_form_id(self.dg)
slider_proto.disabled = disabled
slider_proto.label_visibility.value = get_label_visibility_proto_value(
label_visibility
)
if help is not None:
slider_proto.help = dedent(help)
validate_width(width)
layout_config = LayoutConfig(width=width)
serde = SelectSliderSerde(opt, slider_value, _is_range_value(value))
widget_state = register_widget(
slider_proto.id,
on_change_handler=on_change,
args=args,
kwargs=kwargs,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="double_array_value",
)
if isinstance(widget_state.value, tuple):
widget_state = maybe_coerce_enum_sequence(
cast("RegisterWidgetResult[tuple[T, T]]", widget_state), options, opt
)
else:
widget_state = maybe_coerce_enum(widget_state, options, opt)
if widget_state.value_changed:
slider_proto.value[:] = serde.serialize(widget_state.value)
slider_proto.set_value = True
if ctx:
save_for_app_testing(ctx, element_id, format_func)
self.dg._enqueue("slider", slider_proto, layout_config=layout_config)
return widget_state.value
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/widgets/radio.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from dataclasses import dataclass
from textwrap import dedent
from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast, overload
from typing_extensions import Never
from streamlit.dataframe_util import OptionSequence, convert_anything_to_list
from streamlit.elements.lib.form_utils import current_form_id
from streamlit.elements.lib.layout_utils import (
LayoutConfig,
Width,
validate_width,
)
from streamlit.elements.lib.options_selector_utils import index_, maybe_coerce_enum
from streamlit.elements.lib.policies import (
check_widget_policies,
maybe_raise_label_warnings,
)
from streamlit.elements.lib.utils import (
Key,
LabelVisibility,
compute_and_register_element_id,
get_label_visibility_proto_value,
save_for_app_testing,
to_key,
)
from streamlit.errors import StreamlitAPIException
from streamlit.proto.Radio_pb2 import Radio as RadioProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner import ScriptRunContext, get_script_run_ctx
from streamlit.runtime.state import (
WidgetArgs,
WidgetCallback,
WidgetKwargs,
get_session_state,
register_widget,
)
from streamlit.type_util import (
check_python_comparable,
)
if TYPE_CHECKING:
from collections.abc import Callable, Sequence
from streamlit.delta_generator import DeltaGenerator
T = TypeVar("T")
@dataclass
class RadioSerde(Generic[T]):
options: Sequence[T]
index: int | None
def serialize(self, v: object) -> int | None:
if v is None:
return None
return 0 if len(self.options) == 0 else index_(self.options, v)
def deserialize(self, ui_value: int | None) -> T | None:
idx = ui_value if ui_value is not None else self.index
return (
self.options[idx]
if idx is not None
and len(self.options) > 0
and self.options[idx] is not None
else None
)
class RadioMixin:
@overload
def radio(
self,
label: str,
options: Sequence[Never],
index: int = 0,
format_func: Callable[[Any], Any] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only args:
disabled: bool = False,
horizontal: bool = False,
captions: Sequence[str] | None = None,
label_visibility: LabelVisibility = "visible",
width: Width = "content",
) -> None: ...
@overload
def radio(
self,
label: str,
options: OptionSequence[T],
index: int = 0,
format_func: Callable[[Any], Any] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only args:
disabled: bool = False,
horizontal: bool = False,
captions: Sequence[str] | None = None,
label_visibility: LabelVisibility = "visible",
width: Width = "content",
) -> T: ...
@overload
def radio(
self,
label: str,
options: OptionSequence[T],
index: None,
format_func: Callable[[Any], Any] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only args:
disabled: bool = False,
horizontal: bool = False,
captions: Sequence[str] | None = None,
label_visibility: LabelVisibility = "visible",
width: Width = "content",
) -> T | None: ...
@gather_metrics("radio")
def radio(
self,
label: str,
options: OptionSequence[T],
index: int | None = 0,
format_func: Callable[[Any], Any] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only args:
disabled: bool = False,
horizontal: bool = False,
captions: Sequence[str] | None = None,
label_visibility: LabelVisibility = "visible",
width: Width = "content",
) -> T | None:
r"""Display a radio button widget.
Parameters
----------
label : str
A short label explaining to the user what this radio group is for.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
For accessibility reasons, you should never set an empty label, but
you can hide it with ``label_visibility`` if needed. In the future,
we may disallow empty labels by raising an exception.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
options : Iterable
Labels for the select options in an ``Iterable``. This can be a
``list``, ``set``, or anything supported by ``st.dataframe``. If
``options`` is dataframe-like, the first column will be used. Each
label will be cast to ``str`` internally by default.
Labels can include markdown as described in the ``label`` parameter
and will be cast to str internally by default.
index : int or None
The index of the preselected option on first render. If ``None``,
will initialize empty and return ``None`` until the user selects an option.
Defaults to 0 (the first option).
format_func : function
Function to modify the display of radio options. It receives
the raw option as an argument and should output the label to be
shown for that option. This has no impact on the return value of
the radio.
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. No two widgets may have the same key.
help : str or None
A tooltip that gets displayed next to the widget label. Streamlit
only displays the tooltip when ``label_visibility="visible"``. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
on_change : callable
An optional callback invoked when this radio's value changes.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
disabled : bool
An optional boolean that disables the radio button if set to
``True``. The default is ``False``.
horizontal : bool
An optional boolean, which orients the radio group horizontally.
The default is false (vertical buttons).
captions : iterable of str or None
A list of captions to show below each radio button. If None (default),
no captions are shown.
label_visibility : "visible", "hidden", or "collapsed"
The visibility of the label. The default is ``"visible"``. If this
is ``"hidden"``, Streamlit displays an empty spacer instead of the
label, which can help keep the widget aligned with other widgets.
If this is ``"collapsed"``, Streamlit displays no label or spacer.
width : "content", "stretch", or int
The width of the radio button widget. This can be one of the
following:
- ``"content"`` (default): The width of the widget matches the
width of its content, but doesn't exceed the width of the parent
container.
- ``"stretch"``: The width of the widget matches the width of the
parent container.
- An integer specifying the width in pixels: The widget has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the widget matches the width
of the parent container.
Returns
-------
any
The selected option or ``None`` if no option is selected.
This is a copy of the selected option, not the original.
Example
-------
>>> import streamlit as st
>>>
>>> genre = st.radio(
... "What's your favorite movie genre",
... [":rainbow[Comedy]", "***Drama***", "Documentary :movie_camera:"],
... captions=[
... "Laugh out loud.",
... "Get the popcorn.",
... "Never stop learning.",
... ],
... )
>>>
>>> if genre == ":rainbow[Comedy]":
... st.write("You selected comedy.")
... else:
... st.write("You didn't select comedy.")
.. output::
https://doc-radio.streamlit.app/
height: 300px
To initialize an empty radio widget, use ``None`` as the index value:
>>> import streamlit as st
>>>
>>> genre = st.radio(
... "What's your favorite movie genre",
... [":rainbow[Comedy]", "***Drama***", "Documentary :movie_camera:"],
... index=None,
... )
>>>
>>> st.write("You selected:", genre)
.. output::
https://doc-radio-empty.streamlit.app/
height: 300px
"""
ctx = get_script_run_ctx()
return self._radio(
label=label,
options=options,
index=index,
format_func=format_func,
key=key,
help=help,
on_change=on_change,
args=args,
kwargs=kwargs,
disabled=disabled,
horizontal=horizontal,
captions=captions,
label_visibility=label_visibility,
ctx=ctx,
width=width,
)
def _radio(
self,
label: str,
options: OptionSequence[T],
index: int | None = 0,
format_func: Callable[[Any], Any] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only args:
disabled: bool = False,
horizontal: bool = False,
label_visibility: LabelVisibility = "visible",
captions: Sequence[str] | None = None,
ctx: ScriptRunContext | None,
width: Width = "content",
) -> T | None:
key = to_key(key)
check_widget_policies(
self.dg,
key,
on_change,
default_value=None if index == 0 else index,
)
maybe_raise_label_warnings(label, label_visibility)
validate_width(width, allow_content=True)
layout_config = LayoutConfig(width=width)
opt = convert_anything_to_list(options)
check_python_comparable(opt)
element_id = compute_and_register_element_id(
"radio",
user_key=key,
# Treat provided key as the main widget identity. Only include the
# following parameters in the identity computation since they can
# invalidate the current selection mapping.
# Changes to format_func also invalidate the current selection,
# but this is already handled via the `options` parameter below:
key_as_main_identity={"options"},
dg=self.dg,
label=label,
options=[str(format_func(option)) for option in opt],
index=index,
help=help,
horizontal=horizontal,
captions=captions,
width=width,
)
if not isinstance(index, int) and index is not None:
raise StreamlitAPIException(
f"Radio Value has invalid type: {type(index).__name__}"
)
if index is not None and len(opt) > 0 and not 0 <= index < len(opt):
raise StreamlitAPIException(
"Radio index must be between 0 and length of options"
)
def handle_captions(caption: str | None) -> str:
if caption is None:
return ""
if isinstance(caption, str):
return caption
raise StreamlitAPIException(
f"Radio captions must be strings. Passed type: {type(caption).__name__}"
)
session_state = get_session_state().filtered_state
if key is not None and key in session_state and session_state[key] is None:
index = None
radio_proto = RadioProto()
radio_proto.id = element_id
radio_proto.label = label
if index is not None:
radio_proto.default = index
radio_proto.options[:] = [str(format_func(option)) for option in opt]
radio_proto.form_id = current_form_id(self.dg)
radio_proto.horizontal = horizontal
radio_proto.disabled = disabled
radio_proto.label_visibility.value = get_label_visibility_proto_value(
label_visibility
)
if captions is not None:
radio_proto.captions[:] = map(handle_captions, captions)
if help is not None:
radio_proto.help = dedent(help)
serde = RadioSerde(opt, index)
widget_state = register_widget(
radio_proto.id,
on_change_handler=on_change,
args=args,
kwargs=kwargs,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="int_value",
)
widget_state = maybe_coerce_enum(widget_state, options, opt)
if widget_state.value_changed:
if widget_state.value is not None:
serialized_value = serde.serialize(widget_state.value)
if serialized_value is not None:
radio_proto.value = serialized_value
radio_proto.set_value = True
if ctx:
save_for_app_testing(ctx, element_id, format_func)
self.dg._enqueue("radio", radio_proto, layout_config=layout_config)
return widget_state.value
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/widgets/audio_input.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from dataclasses import dataclass
from textwrap import dedent
from typing import TYPE_CHECKING, TypeAlias, cast
from streamlit.elements.lib.file_uploader_utils import enforce_filename_restriction
from streamlit.elements.lib.form_utils import current_form_id
from streamlit.elements.lib.layout_utils import LayoutConfig, validate_width
from streamlit.elements.lib.policies import (
check_widget_policies,
maybe_raise_label_warnings,
)
from streamlit.elements.lib.utils import (
Key,
LabelVisibility,
compute_and_register_element_id,
get_label_visibility_proto_value,
to_key,
)
from streamlit.elements.widgets.file_uploader import _get_upload_files
from streamlit.errors import StreamlitAPIException
from streamlit.proto.AudioInput_pb2 import AudioInput as AudioInputProto
from streamlit.proto.Common_pb2 import FileUploaderState as FileUploaderStateProto
from streamlit.proto.Common_pb2 import UploadedFileInfo as UploadedFileInfoProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner import ScriptRunContext, get_script_run_ctx
from streamlit.runtime.state import (
WidgetArgs,
WidgetCallback,
WidgetKwargs,
register_widget,
)
from streamlit.runtime.uploaded_file_manager import DeletedFile, UploadedFile
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
from streamlit.elements.lib.layout_utils import WidthWithoutContent
SomeUploadedAudioFile: TypeAlias = UploadedFile | DeletedFile | None
# Allowed sample rates for audio recording
ALLOWED_SAMPLE_RATES = {8000, 11025, 16000, 22050, 24000, 32000, 44100, 48000}
@dataclass
class AudioInputSerde:
def serialize(
self,
audio_file: SomeUploadedAudioFile,
) -> FileUploaderStateProto:
state_proto = FileUploaderStateProto()
if audio_file is None or isinstance(audio_file, DeletedFile):
return state_proto
file_info: UploadedFileInfoProto = state_proto.uploaded_file_info.add()
file_info.file_id = audio_file.file_id
file_info.name = audio_file.name
file_info.size = audio_file.size
file_info.file_urls.CopyFrom(audio_file._file_urls)
return state_proto
def deserialize(
self, ui_value: FileUploaderStateProto | None
) -> SomeUploadedAudioFile:
upload_files = _get_upload_files(ui_value)
return_value = None if len(upload_files) == 0 else upload_files[0]
if return_value is not None and not isinstance(return_value, DeletedFile):
enforce_filename_restriction(return_value.name, [".wav"])
return return_value
class AudioInputMixin:
@gather_metrics("audio_input")
def audio_input(
self,
label: str,
*,
sample_rate: int | None = 16000,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> UploadedFile | None:
r"""Display a widget that returns an audio recording from the user's microphone.
Parameters
----------
label : str
A short label explaining to the user what this widget is used for.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
For accessibility reasons, you should never set an empty label, but
you can hide it with ``label_visibility`` if needed. In the future,
we may disallow empty labels by raising an exception.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
sample_rate : int or None
The target sample rate for the audio recording in Hz. This
defaults to ``16000``, which is optimal for speech recognition.
The following values are supported: ``8000`` (telephone quality),
``11025``, ``16000`` (speech-recognition quality), ``22050``,
``24000``, ``32000``, ``44100``, ``48000`` (high-quality), or
``None``. If this is ``None``, the widget uses the browser's
default sample rate (typically 44100 or 48000 Hz).
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. No two widgets may have the same key.
help : str or None
A tooltip that gets displayed next to the widget label. Streamlit
only displays the tooltip when ``label_visibility="visible"``. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
on_change : callable
An optional callback invoked when this audio input's value
changes.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
disabled : bool
An optional boolean that disables the audio input if set to
``True``. Default is ``False``.
label_visibility : "visible", "hidden", or "collapsed"
The visibility of the label. The default is ``"visible"``. If this
is ``"hidden"``, Streamlit displays an empty spacer instead of the
label, which can help keep the widget aligned with other widgets.
If this is ``"collapsed"``, Streamlit displays no label or spacer.
width : "stretch" or int
The width of the audio input widget. This can be one of the following:
- ``"stretch"`` (default): The width of the widget matches the
width of the parent container.
- An integer specifying the width in pixels: The widget has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the widget matches the width
of the parent container.
Returns
-------
None or UploadedFile
The ``UploadedFile`` class is a subclass of ``BytesIO``, and
therefore is "file-like". This means you can pass an instance of it
anywhere a file is expected. The MIME type for the audio data is
``audio/wav``.
.. Note::
The resulting ``UploadedFile`` is subject to the size
limitation configured in ``server.maxUploadSize``. If you
expect large sound files, update the configuration option
appropriately.
Examples
--------
*Example 1:* Record a voice message and play it back.*
The default sample rate of 16000 Hz is optimal for speech recognition.
>>> import streamlit as st
>>>
>>> audio_value = st.audio_input("Record a voice message")
>>>
>>> if audio_value:
... st.audio(audio_value)
.. output::
https://doc-audio-input.streamlit.app/
height: 260px
*Example 2:* Record high-fidelity audio and play it back.*
Higher sample rates can create higher-quality, larger audio files. This
might require a nicer microphone to fully appreciate the difference.
>>> import streamlit as st
>>>
>>> audio_value = st.audio_input("Record high quality audio", sample_rate=48000)
>>>
>>> if audio_value:
... st.audio(audio_value)
.. output::
https://doc-audio-input-high-rate.streamlit.app/
height: 260px
"""
# Validate sample_rate parameter
if sample_rate is not None and sample_rate not in ALLOWED_SAMPLE_RATES:
raise StreamlitAPIException(
f"Invalid sample_rate: {sample_rate}. "
f"Must be one of {sorted(ALLOWED_SAMPLE_RATES)} Hz, or None for browser default."
)
ctx = get_script_run_ctx()
return self._audio_input(
label=label,
sample_rate=sample_rate,
key=key,
help=help,
on_change=on_change,
args=args,
kwargs=kwargs,
disabled=disabled,
label_visibility=label_visibility,
width=width,
ctx=ctx,
)
def _audio_input(
self,
label: str,
sample_rate: int | None = 16000,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
ctx: ScriptRunContext | None = None,
) -> UploadedFile | None:
key = to_key(key)
check_widget_policies(
self.dg,
key,
on_change,
default_value=None,
writes_allowed=False,
)
maybe_raise_label_warnings(label, label_visibility)
element_id = compute_and_register_element_id(
"audio_input",
user_key=key,
# Treat the provided key as the main identity.
key_as_main_identity=True,
dg=self.dg,
label=label,
help=help,
width=width,
sample_rate=sample_rate,
)
audio_input_proto = AudioInputProto()
audio_input_proto.id = element_id
audio_input_proto.label = label
audio_input_proto.form_id = current_form_id(self.dg)
audio_input_proto.disabled = disabled
audio_input_proto.label_visibility.value = get_label_visibility_proto_value(
label_visibility
)
# Set sample_rate in protobuf if specified
if sample_rate is not None:
audio_input_proto.sample_rate = sample_rate
if label and help is not None:
audio_input_proto.help = dedent(help)
validate_width(width)
layout_config = LayoutConfig(width=width)
serde = AudioInputSerde()
audio_input_state = register_widget(
audio_input_proto.id,
on_change_handler=on_change,
args=args,
kwargs=kwargs,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="file_uploader_state_value",
)
self.dg._enqueue("audio_input", audio_input_proto, layout_config=layout_config)
if isinstance(audio_input_state.value, DeletedFile):
return None
return audio_input_state.value
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/widgets/selectbox.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from textwrap import dedent
from typing import (
TYPE_CHECKING,
Any,
Generic,
Literal,
TypeVar,
cast,
overload,
)
from typing_extensions import Never
from streamlit.dataframe_util import OptionSequence, convert_anything_to_list
from streamlit.elements.lib.form_utils import current_form_id
from streamlit.elements.lib.layout_utils import (
LayoutConfig,
WidthWithoutContent,
validate_width,
)
from streamlit.elements.lib.options_selector_utils import (
create_mappings,
index_,
maybe_coerce_enum,
)
from streamlit.elements.lib.policies import (
check_widget_policies,
maybe_raise_label_warnings,
)
from streamlit.elements.lib.utils import (
Key,
LabelVisibility,
compute_and_register_element_id,
get_label_visibility_proto_value,
save_for_app_testing,
to_key,
)
from streamlit.errors import StreamlitAPIException
from streamlit.proto.Selectbox_pb2 import Selectbox as SelectboxProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner import ScriptRunContext, get_script_run_ctx
from streamlit.runtime.state import (
WidgetArgs,
WidgetCallback,
WidgetKwargs,
get_session_state,
register_widget,
)
from streamlit.type_util import (
check_python_comparable,
)
if TYPE_CHECKING:
from collections.abc import Callable, Sequence
from streamlit.delta_generator import DeltaGenerator
T = TypeVar("T")
class SelectboxSerde(Generic[T]):
options: Sequence[T]
formatted_options: list[str]
formatted_option_to_option_index: dict[str, int]
default_option_index: int | None
def __init__(
self,
options: Sequence[T],
*,
formatted_options: list[str],
formatted_option_to_option_index: dict[str, int],
default_option_index: int | None = None,
) -> None:
"""Initialize the SelectboxSerde.
We do not store an option_to_formatted_option mapping because the generic
options might not be hashable, which would raise a RuntimeError. So we do
two lookups: option -> index -> formatted_option[index].
Parameters
----------
options : Sequence[T]
The sequence of selectable options.
formatted_options : list[str]
The string representations of each option. The formatted_options correspond
to the options sequence by index.
formatted_option_to_option_index : dict[str, int]
A mapping from formatted option strings to their corresponding indices in
the options sequence.
default_option_index : int or None, optional
The index of the default option to use when no selection is made.
If None, no default option is selected.
"""
self.options = options
self.formatted_options = formatted_options
self.formatted_option_to_option_index = formatted_option_to_option_index
self.default_option_index = default_option_index
def serialize(self, v: T | str | None) -> str | None:
if v is None:
return None
if len(self.options) == 0:
return ""
# we don't check for isinstance(v, str) because this could lead to wrong
# results if v is a string that is part of the options itself as it would
# skip formatting in that case
try:
option_index = index_(self.options, v)
return self.formatted_options[option_index]
except ValueError:
# we know that v is a string, otherwise it would have been found in the
# options
return cast("str", v)
def deserialize(self, ui_value: str | None) -> T | str | None:
# check if the option is pointing to a generic option type T,
# otherwise return the option itself
if ui_value is None:
return (
self.options[self.default_option_index]
if self.default_option_index is not None and len(self.options) > 0
else None
)
option_index = self.formatted_option_to_option_index.get(ui_value)
return self.options[option_index] if option_index is not None else ui_value
class SelectboxMixin:
@overload
def selectbox(
self,
label: str,
options: Sequence[Never], # Type for empty or Never-inferred options
index: int = 0,
format_func: Callable[[Any], str] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
accept_new_options: Literal[False] = False,
width: WidthWithoutContent = "stretch",
) -> None: ... # Returns None if options is empty and accept_new_options is False
@overload
def selectbox(
self,
label: str,
options: OptionSequence[T],
index: int = 0,
format_func: Callable[[Any], str] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
accept_new_options: Literal[False] = False,
width: WidthWithoutContent = "stretch",
) -> T: ...
@overload
def selectbox(
self,
label: str,
options: OptionSequence[T],
index: int = 0,
format_func: Callable[[Any], str] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
accept_new_options: Literal[True] = True,
width: WidthWithoutContent = "stretch",
) -> T | str: ...
@overload
def selectbox(
self,
label: str,
options: OptionSequence[T],
index: None,
format_func: Callable[[Any], str] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
accept_new_options: Literal[False] = False,
width: WidthWithoutContent = "stretch",
) -> T | None: ...
@overload
def selectbox(
self,
label: str,
options: OptionSequence[T],
index: None,
format_func: Callable[[Any], str] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
accept_new_options: Literal[True] = True,
width: WidthWithoutContent = "stretch",
) -> T | str | None: ...
@overload
def selectbox(
self,
label: str,
options: OptionSequence[T],
index: int | None = 0,
format_func: Callable[[Any], str] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
accept_new_options: bool = False,
width: WidthWithoutContent = "stretch",
) -> T | str | None: ...
@gather_metrics("selectbox")
def selectbox(
self,
label: str,
options: OptionSequence[T],
index: int | None = 0,
format_func: Callable[[Any], str] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
accept_new_options: bool = False,
width: WidthWithoutContent = "stretch",
) -> T | str | None:
r"""Display a select widget.
Parameters
----------
label : str
A short label explaining to the user what this select widget is for.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
For accessibility reasons, you should never set an empty label, but
you can hide it with ``label_visibility`` if needed. In the future,
we may disallow empty labels by raising an exception.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
options : Iterable
Labels for the select options in an ``Iterable``. This can be a
``list``, ``set``, or anything supported by ``st.dataframe``. If
``options`` is dataframe-like, the first column will be used. Each
label will be cast to ``str`` internally by default.
index : int or None
The index of the preselected option on first render. If ``None``,
will initialize empty and return ``None`` until the user selects an option.
Defaults to 0 (the first option).
format_func : function
Function to modify the display of the options. It receives
the raw option as an argument and should output the label to be
shown for that option. This has no impact on the return value of
the command.
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. No two widgets may have the same key.
help : str or None
A tooltip that gets displayed next to the widget label. Streamlit
only displays the tooltip when ``label_visibility="visible"``. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
on_change : callable
An optional callback invoked when this selectbox's value changes.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
placeholder : str or None
A string to display when no options are selected.
If this is ``None`` (default), the widget displays placeholder text
based on the widget's configuration:
- "Choose an option" is displayed when options are available and
``accept_new_options=False``.
- "Choose or add an option" is displayed when options are available
and ``accept_new_options=True``.
- "Add an option" is displayed when no options are available and
``accept_new_options=True``.
- "No options to select" is displayed when no options are available
and ``accept_new_options=False``. The widget is also disabled in
this case.
disabled : bool
An optional boolean that disables the selectbox if set to ``True``.
The default is ``False``.
label_visibility : "visible", "hidden", or "collapsed"
The visibility of the label. The default is ``"visible"``. If this
is ``"hidden"``, Streamlit displays an empty spacer instead of the
label, which can help keep the widget aligned with other widgets.
If this is ``"collapsed"``, Streamlit displays no label or spacer.
accept_new_options : bool
Whether the user can add a selection that isn't included in ``options``.
If this is ``False`` (default), the user can only select from the
items in ``options``. If this is ``True``, the user can enter a new
item that doesn't exist in ``options``.
When a user enters a new item, it is returned by the widget as a
string. The new item is not added to the widget's drop-down menu.
Streamlit will use a case-insensitive match from ``options`` before
adding a new item.
width : "stretch" or int
The width of the selectbox widget. This can be one of the
following:
- ``"stretch"`` (default): The width of the widget matches the
width of the parent container.
- An integer specifying the width in pixels: The widget has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the widget matches the width
of the parent container.
Returns
-------
any
The selected option or ``None`` if no option is selected.
This is a copy of the selected option, not the original.
Examples
--------
**Example 1: Use a basic selectbox widget**
If no index is provided, the first option is selected by default.
>>> import streamlit as st
>>>
>>> option = st.selectbox(
... "How would you like to be contacted?",
... ("Email", "Home phone", "Mobile phone"),
... )
>>>
>>> st.write("You selected:", option)
.. output::
https://doc-selectbox.streamlit.app/
height: 320px
**Example 2: Use a selectbox widget with no initial selection**
To initialize an empty selectbox, use ``None`` as the index value.
>>> import streamlit as st
>>>
>>> option = st.selectbox(
... "How would you like to be contacted?",
... ("Email", "Home phone", "Mobile phone"),
... index=None,
... placeholder="Select contact method...",
... )
>>>
>>> st.write("You selected:", option)
.. output::
https://doc-selectbox-empty.streamlit.app/
height: 320px
**Example 3: Let users add a new option**
To allow users to add a new option that isn't included in the
``options`` list, use the ``accept_new_options=True`` parameter. You
can also customize the placeholder text.
>>> import streamlit as st
>>>
>>> option = st.selectbox(
... "Default email",
... ["foo@example.com", "bar@example.com", "baz@example.com"],
... index=None,
... placeholder="Select a saved email or enter a new one",
... accept_new_options=True,
... )
>>>
>>> st.write("You selected:", option)
.. output::
https://doc-selectbox-accept-new-options.streamlit.app/
height: 320px
"""
ctx = get_script_run_ctx()
return self._selectbox(
label=label,
options=options,
index=index,
format_func=format_func,
key=key,
help=help,
on_change=on_change,
args=args,
kwargs=kwargs,
placeholder=placeholder,
disabled=disabled,
label_visibility=label_visibility,
accept_new_options=accept_new_options,
width=width,
ctx=ctx,
)
def _selectbox(
self,
label: str,
options: OptionSequence[T],
index: int | None = 0,
format_func: Callable[[Any], Any] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
accept_new_options: bool = False,
width: WidthWithoutContent = "stretch",
ctx: ScriptRunContext | None = None,
) -> T | str | None:
key = to_key(key)
check_widget_policies(
self.dg,
key,
on_change,
default_value=None if index == 0 else index,
)
maybe_raise_label_warnings(label, label_visibility)
opt = convert_anything_to_list(options)
check_python_comparable(opt)
if not isinstance(index, int) and index is not None:
raise StreamlitAPIException(
f"Selectbox Value has invalid type: {type(index).__name__}"
)
if index is not None and len(opt) > 0 and not 0 <= index < len(opt):
raise StreamlitAPIException(
"Selectbox index must be greater than or equal to 0 "
"and less than the length of options."
)
# Convert empty string to single space to distinguish from None:
# - None (default) → "" → Frontend shows contextual placeholders
# - "" (explicit empty) → " " → Frontend shows empty placeholder
# - "Custom" → "Custom" → Frontend shows custom placeholder
if placeholder == "":
placeholder = " "
formatted_options, formatted_option_to_option_index = create_mappings(
opt, format_func
)
element_id = compute_and_register_element_id(
"selectbox",
user_key=key,
# Treat the provided key as the main identity. Only include
# the options and accept_new_options in the identity computation
# as those can invalidate the current selection.
# Changes to format_func also invalidate the current selection,
# but this is already handled via the `options` parameter below:
key_as_main_identity={"options", "accept_new_options"},
dg=self.dg,
label=label,
options=formatted_options,
index=index,
help=help,
placeholder=placeholder,
accept_new_options=accept_new_options,
width=width,
)
session_state = get_session_state().filtered_state
if key is not None and key in session_state and session_state[key] is None:
index = None
selectbox_proto = SelectboxProto()
selectbox_proto.id = element_id
selectbox_proto.label = label
if index is not None:
selectbox_proto.default = index
selectbox_proto.options[:] = formatted_options
selectbox_proto.form_id = current_form_id(self.dg)
selectbox_proto.placeholder = placeholder or ""
selectbox_proto.disabled = disabled
selectbox_proto.label_visibility.value = get_label_visibility_proto_value(
label_visibility
)
selectbox_proto.accept_new_options = accept_new_options
if help is not None:
selectbox_proto.help = dedent(help)
serde = SelectboxSerde(
opt,
formatted_options=formatted_options,
formatted_option_to_option_index=formatted_option_to_option_index,
default_option_index=index,
)
widget_state = register_widget(
selectbox_proto.id,
on_change_handler=on_change,
args=args,
kwargs=kwargs,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="string_value",
)
widget_state = maybe_coerce_enum(widget_state, options, opt)
if widget_state.value_changed:
serialized_value = serde.serialize(widget_state.value)
if serialized_value is not None:
selectbox_proto.raw_value = serialized_value
selectbox_proto.set_value = True
validate_width(width)
layout_config = LayoutConfig(width=width)
if ctx:
save_for_app_testing(ctx, element_id, format_func)
self.dg._enqueue("selectbox", selectbox_proto, layout_config=layout_config)
return widget_state.value
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/widgets/time_widgets.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import re
from collections.abc import Sequence
from dataclasses import dataclass
from datetime import date, datetime, time, timedelta
from textwrap import dedent
from typing import (
TYPE_CHECKING,
Any,
Final,
Literal,
TypeAlias,
cast,
overload,
)
from streamlit.elements.lib.form_utils import current_form_id
from streamlit.elements.lib.layout_utils import (
LayoutConfig,
WidthWithoutContent,
validate_width,
)
from streamlit.elements.lib.policies import (
check_widget_policies,
maybe_raise_label_warnings,
)
from streamlit.elements.lib.utils import (
Key,
LabelVisibility,
compute_and_register_element_id,
get_label_visibility_proto_value,
to_key,
)
from streamlit.errors import StreamlitAPIException
from streamlit.proto.DateInput_pb2 import DateInput as DateInputProto
from streamlit.proto.DateTimeInput_pb2 import DateTimeInput as DateTimeInputProto
from streamlit.proto.TimeInput_pb2 import TimeInput as TimeInputProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner import ScriptRunContext, get_script_run_ctx
from streamlit.runtime.state import (
WidgetArgs,
WidgetCallback,
WidgetKwargs,
get_session_state,
register_widget,
)
from streamlit.time_util import adjust_years
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
# Type for things that point to a specific time (even if a default time, though not None).
TimeValue: TypeAlias = time | datetime | str | Literal["now"]
DateTimeScalarValue: TypeAlias = datetime | date | time | str | Literal["now"]
DateTimeValue: TypeAlias = DateTimeScalarValue | None
# Type for things that point to a specific date (even if a default date, including None).
NullableScalarDateValue: TypeAlias = date | datetime | str | Literal["today"] | None
# The accepted input value for st.date_input. Can be a date scalar or a date range.
DateValue: TypeAlias = NullableScalarDateValue | Sequence[NullableScalarDateValue]
# The return value of st.date_input.
DateWidgetRangeReturn: TypeAlias = tuple[()] | tuple[date] | tuple[date, date]
DateWidgetReturn: TypeAlias = date | DateWidgetRangeReturn | None
DEFAULT_STEP_MINUTES: Final = 15
ALLOWED_DATE_FORMATS: Final = re.compile(
r"^(YYYY[/.\-]MM[/.\-]DD|DD[/.\-]MM[/.\-]YYYY|MM[/.\-]DD[/.\-]YYYY)$"
)
_DATETIME_UI_FORMAT: Final = "%Y/%m/%d, %H:%M"
_DEFAULT_MIN_BOUND_TIME: Final = time(hour=0, minute=0)
_DEFAULT_MAX_BOUND_TIME: Final = time(hour=23, minute=59)
def _convert_timelike_to_time(value: TimeValue) -> time:
if value == "now":
# Set value default.
return datetime.now().time().replace(second=0, microsecond=0)
if isinstance(value, str):
try:
return time.fromisoformat(value)
except ValueError:
try:
return (
datetime.fromisoformat(value)
.time()
.replace(second=0, microsecond=0)
)
except ValueError:
# We throw an error below.
pass
if isinstance(value, datetime):
return value.time().replace(second=0, microsecond=0)
if isinstance(value, time):
return value
raise StreamlitAPIException(
"The type of value should be one of datetime, time, ISO string or None"
)
def _convert_datelike_to_date(
value: NullableScalarDateValue,
) -> date:
if isinstance(value, datetime):
return value.date()
if isinstance(value, date):
return value
if value in {"today"}:
return datetime.now().date()
if isinstance(value, str):
try:
return date.fromisoformat(value)
except ValueError:
try:
return datetime.fromisoformat(value).date()
except ValueError:
# We throw an error below.
pass
raise StreamlitAPIException(
'Date value should either be an date/datetime or an ISO string or "today"'
)
def _parse_date_value(value: DateValue) -> tuple[list[date] | None, bool]:
if value is None:
return None, False
value_tuple: Sequence[NullableScalarDateValue]
if isinstance(value, Sequence) and not isinstance(value, str):
is_range = True
value_tuple = value
else:
is_range = False
value_tuple = [cast("NullableScalarDateValue", value)]
if len(value_tuple) not in {0, 1, 2}:
raise StreamlitAPIException(
"DateInput value should either be an date/datetime or a list/tuple of "
"0 - 2 date/datetime values"
)
parsed_dates = [_convert_datelike_to_date(v) for v in value_tuple] # ty: ignore[invalid-argument-type]
return parsed_dates, is_range
def _parse_min_date(
min_value: NullableScalarDateValue,
parsed_dates: Sequence[date] | None,
) -> date:
parsed_min_date: date
if isinstance(min_value, (datetime, date, str)):
parsed_min_date = _convert_datelike_to_date(min_value)
elif min_value is None:
if parsed_dates:
parsed_min_date = adjust_years(parsed_dates[0], years=-10)
else:
parsed_min_date = adjust_years(date.today(), years=-10)
else:
raise StreamlitAPIException(
"DateInput min should either be a date/datetime or None"
)
return parsed_min_date
def _parse_max_date(
max_value: NullableScalarDateValue,
parsed_dates: Sequence[date] | None,
) -> date:
parsed_max_date: date
if isinstance(max_value, (datetime, date, str)):
parsed_max_date = _convert_datelike_to_date(max_value)
elif max_value is None:
if parsed_dates:
parsed_max_date = adjust_years(parsed_dates[-1], years=10)
else:
parsed_max_date = adjust_years(date.today(), years=10)
else:
raise StreamlitAPIException(
"DateInput max should either be a date/datetime or None"
)
return parsed_max_date
def _normalize_time(value: time) -> time:
"""Return a time without seconds, microseconds, or timezone info."""
return value.replace(second=0, microsecond=0, tzinfo=None)
def _normalize_datetime_value(value: datetime) -> datetime:
"""Return a datetime without seconds, microseconds, or timezone info."""
if value.tzinfo is not None:
value = value.replace(tzinfo=None)
return value.replace(second=0, microsecond=0)
def _combine_date_time(component_date: date, component_time: time) -> datetime:
"""Combine a date and time into a normalized datetime."""
return datetime.combine(component_date, _normalize_time(component_time))
def _try_parse_datetime_with_format(value: str, fmt: str) -> datetime | None:
"""Try to parse a datetime string with a specific format."""
try:
return datetime.strptime(value, fmt)
except ValueError:
return None
def _convert_datetimelike_to_datetime(
value: DateTimeScalarValue,
*,
fallback_date: date,
fallback_time: time,
) -> datetime:
"""Convert supported datetime inputs into a normalized datetime."""
fallback_time = _normalize_time(fallback_time)
if value == "now":
return _normalize_datetime_value(datetime.now())
if isinstance(value, datetime):
return _normalize_datetime_value(value)
if isinstance(value, date) and not isinstance(value, datetime):
return _combine_date_time(value, fallback_time)
if isinstance(value, time):
return _combine_date_time(fallback_date, value)
if isinstance(value, str):
stripped_value = value.strip()
try:
parsed_dt = datetime.fromisoformat(stripped_value)
return _normalize_datetime_value(parsed_dt)
except ValueError:
pass
for fmt in (
"%Y/%m/%d %H:%M",
"%Y/%m/%d %H:%M:%S",
"%Y-%m-%d %H:%M",
"%Y-%m-%d %H:%M:%S",
):
maybe_parsed_dt = _try_parse_datetime_with_format(stripped_value, fmt)
if maybe_parsed_dt is not None:
return _normalize_datetime_value(maybe_parsed_dt)
try:
parsed_date = date.fromisoformat(stripped_value)
return _combine_date_time(parsed_date, fallback_time)
except ValueError:
pass
try:
parsed_time = time.fromisoformat(stripped_value)
return _combine_date_time(fallback_date, parsed_time)
except ValueError:
pass
raise StreamlitAPIException(
"The type of value should be one of datetime, date, time, ISO string, or 'now'."
)
def _default_min_datetime(base_date: date) -> datetime:
return _combine_date_time(
adjust_years(base_date, years=-10), _DEFAULT_MIN_BOUND_TIME
)
def _default_max_datetime(base_date: date) -> datetime:
return _combine_date_time(
adjust_years(base_date, years=10), _DEFAULT_MAX_BOUND_TIME
)
def _datetime_to_proto_string(value: datetime) -> str:
return _normalize_datetime_value(value).strftime(_DATETIME_UI_FORMAT)
@dataclass(frozen=True)
class _DateTimeInputValues:
value: datetime | None
min: datetime
max: datetime
@classmethod
def from_raw_values(
cls,
value: DateTimeValue,
min_value: DateTimeValue,
max_value: DateTimeValue,
) -> _DateTimeInputValues:
parsed_value = (
None
if value is None
else _convert_datetimelike_to_datetime(
value,
fallback_date=date.today(),
fallback_time=_DEFAULT_MIN_BOUND_TIME,
)
)
base_date_for_bounds = (
parsed_value.date() if parsed_value is not None else date.today()
)
parsed_min = (
_default_min_datetime(base_date_for_bounds)
if min_value is None
else _convert_datetimelike_to_datetime(
min_value,
fallback_date=base_date_for_bounds,
fallback_time=_DEFAULT_MIN_BOUND_TIME,
)
)
parsed_max = (
_default_max_datetime(base_date_for_bounds)
if max_value is None
else _convert_datetimelike_to_datetime(
max_value,
fallback_date=base_date_for_bounds,
fallback_time=_DEFAULT_MAX_BOUND_TIME,
)
)
return cls(
value=parsed_value,
min=parsed_min,
max=parsed_max,
)
def __post_init__(self) -> None:
if self.min > self.max:
raise StreamlitAPIException(
f"The `min_value`, set to {self.min}, shouldn't be larger "
f"than the `max_value`, set to {self.max}."
)
if self.value is not None and (self.value < self.min or self.value > self.max):
raise StreamlitAPIException(
f"The default `value` of {self.value} must lie between the `min_value` "
f"of {self.min} and the `max_value` of {self.max}, inclusively."
)
@dataclass(frozen=True)
class _DateInputValues:
value: Sequence[date] | None
is_range: bool
max: date
min: date
@classmethod
def from_raw_values(
cls,
value: DateValue,
min_value: NullableScalarDateValue,
max_value: NullableScalarDateValue,
) -> _DateInputValues:
parsed_value, is_range = _parse_date_value(value=value)
parsed_min = _parse_min_date(
min_value=min_value,
parsed_dates=parsed_value,
)
parsed_max = _parse_max_date(
max_value=max_value,
parsed_dates=parsed_value,
)
if value == "today":
v = cast("list[date]", parsed_value)[0]
if v < parsed_min:
parsed_value = [parsed_min]
if v > parsed_max:
parsed_value = [parsed_max]
return cls(
value=parsed_value,
is_range=is_range,
min=parsed_min,
max=parsed_max,
)
def __post_init__(self) -> None:
if self.min > self.max:
raise StreamlitAPIException(
f"The `min_value`, set to {self.min}, shouldn't be larger "
f"than the `max_value`, set to {self.max}."
)
if self.value:
start_value = self.value[0]
end_value = self.value[-1]
if (start_value < self.min) or (end_value > self.max):
raise StreamlitAPIException(
f"The default `value` of {self.value} "
f"must lie between the `min_value` of {self.min} "
f"and the `max_value` of {self.max}, inclusively."
)
@dataclass
class DateTimeInputSerde:
value: datetime | None
min: datetime
max: datetime
def deserialize(self, ui_value: list[str] | None) -> datetime | None:
if ui_value is not None and len(ui_value) > 0:
deserialized = _normalize_datetime_value(
datetime.strptime(ui_value[0], _DATETIME_UI_FORMAT)
)
# Validate against min/max bounds
# If the value is out of bounds, return the previous valid value
if deserialized < self.min or deserialized > self.max:
return self.value
return deserialized
return self.value
def serialize(self, v: datetime | None) -> list[str]:
if v is None:
return []
return [_datetime_to_proto_string(v)]
@dataclass
class TimeInputSerde:
value: time | None
def deserialize(self, ui_value: str | None) -> time | None:
return (
datetime.strptime(ui_value, "%H:%M").time()
if ui_value is not None
else self.value
)
def serialize(self, v: datetime | time | None) -> str | None:
if v is None:
return None
if isinstance(v, datetime):
v = v.time()
return time.strftime(v, "%H:%M")
@dataclass
class DateInputSerde:
value: _DateInputValues
def deserialize(self, ui_value: Any) -> DateWidgetReturn:
return_value: Sequence[date] | None
if ui_value is not None:
return_value = tuple(
datetime.strptime(v, "%Y/%m/%d").date() for v in ui_value
)
else:
return_value = self.value.value
if return_value is None or len(return_value) == 0:
return () if self.value.is_range else None
if not self.value.is_range:
return return_value[0]
return cast("DateWidgetReturn", tuple(return_value))
def serialize(self, v: DateWidgetReturn) -> list[str]:
if v is None:
return []
to_serialize = list(v) if isinstance(v, Sequence) else [v]
return [date.strftime(v, "%Y/%m/%d") for v in to_serialize]
class TimeWidgetsMixin:
@overload
def time_input(
self,
label: str,
value: TimeValue = "now",
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
step: int | timedelta = timedelta(minutes=DEFAULT_STEP_MINUTES),
width: WidthWithoutContent = "stretch",
) -> time:
pass
@overload
def time_input(
self,
label: str,
value: None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
step: int | timedelta = timedelta(minutes=DEFAULT_STEP_MINUTES),
width: WidthWithoutContent = "stretch",
) -> time | None:
pass
@gather_metrics("time_input")
def time_input(
self,
label: str,
value: TimeValue | None = "now",
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
step: int | timedelta = timedelta(minutes=DEFAULT_STEP_MINUTES),
width: WidthWithoutContent = "stretch",
) -> time | None:
r"""Display a time input widget.
Parameters
----------
label : str
A short label explaining to the user what this time input is for.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
For accessibility reasons, you should never set an empty label, but
you can hide it with ``label_visibility`` if needed. In the future,
we may disallow empty labels by raising an exception.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
value : "now", datetime.time, datetime.datetime, str, or None
The value of this widget when it first renders. This can be one of
the following:
- ``"now"`` (default): The widget initializes with the current time.
- A ``datetime.time`` or ``datetime.datetime`` object: The widget
initializes with the given time, ignoring any date if included.
- An ISO-formatted time (hh:mm[:ss.sss]) or datetime
(YYYY-MM-DD hh:mm[:ss]) string: The widget initializes with the
given time, ignoring any date if included.
- ``None``: The widget initializes with no time and returns
``None`` until the user selects a time.
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. No two widgets may have the same key.
help : str or None
A tooltip that gets displayed next to the widget label. Streamlit
only displays the tooltip when ``label_visibility="visible"``. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
on_change : callable
An optional callback invoked when this time_input's value changes.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
disabled : bool
An optional boolean that disables the time input if set to
``True``. The default is ``False``.
label_visibility : "visible", "hidden", or "collapsed"
The visibility of the label. The default is ``"visible"``. If this
is ``"hidden"``, Streamlit displays an empty spacer instead of the
label, which can help keep the widget aligned with other widgets.
If this is ``"collapsed"``, Streamlit displays no label or spacer.
step : int or timedelta
The stepping interval in seconds. This defaults to ``900`` (15
minutes). You can also pass a ``datetime.timedelta`` object. The
value must be between 60 seconds and 23 hours.
width : "stretch" or int
The width of the time input widget. This can be one of the following:
- ``"stretch"`` (default): The width of the widget matches the
width of the parent container.
- An integer specifying the width in pixels: The widget has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the widget matches the width
of the parent container.
Returns
-------
datetime.time or None
The current value of the time input widget or ``None`` if no time has been
selected.
Example
-------
**Example 1: Basic usage**
>>> import datetime
>>> import streamlit as st
>>>
>>> t = st.time_input("Set an alarm for", datetime.time(8, 45))
>>> st.write("Alarm is set for", t)
.. output::
https://doc-time-input.streamlit.app/
height: 260px
**Example 2: Empty initial value**
To initialize an empty time input, use ``None`` as the value:
>>> import datetime
>>> import streamlit as st
>>>
>>> t = st.time_input("Set an alarm for", value=None)
>>> st.write("Alarm is set for", t)
.. output::
https://doc-time-input-empty.streamlit.app/
height: 260px
"""
ctx = get_script_run_ctx()
return self._time_input(
label=label,
value=value,
key=key,
help=help,
on_change=on_change,
args=args,
kwargs=kwargs,
disabled=disabled,
label_visibility=label_visibility,
step=step,
width=width,
ctx=ctx,
)
def _time_input(
self,
label: str,
value: TimeValue | None = "now",
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
step: int | timedelta = timedelta(minutes=DEFAULT_STEP_MINUTES),
width: WidthWithoutContent = "stretch",
ctx: ScriptRunContext | None = None,
) -> time | None:
key = to_key(key)
check_widget_policies(
self.dg,
key,
on_change,
default_value=value if value != "now" else None,
)
maybe_raise_label_warnings(label, label_visibility)
parsed_time: time | None
parsed_time = None if value is None else _convert_timelike_to_time(value)
element_id = compute_and_register_element_id(
"time_input",
user_key=key,
# Ensure stable ID when key is provided; only whitelist step since it
# affects the selection granularity and available options.
key_as_main_identity={"step"},
dg=self.dg,
label=label,
value=parsed_time if isinstance(value, (datetime, time)) else value,
help=help,
step=step,
width=width,
)
del value
session_state = get_session_state().filtered_state
if key is not None and key in session_state and session_state[key] is None:
parsed_time = None
time_input_proto = TimeInputProto()
time_input_proto.id = element_id
time_input_proto.label = label
if parsed_time is not None:
time_input_proto.default = time.strftime(parsed_time, "%H:%M")
time_input_proto.form_id = current_form_id(self.dg)
if not isinstance(step, (int, timedelta)):
raise StreamlitAPIException(
f"`step` can only be `int` or `timedelta` but {type(step)} is provided."
)
if isinstance(step, timedelta):
step = step.seconds
if step < 60 or step > timedelta(hours=23).seconds:
raise StreamlitAPIException(
f"`step` must be between 60 seconds and 23 hours but is currently set to {step} seconds."
)
time_input_proto.step = step
time_input_proto.disabled = disabled
time_input_proto.label_visibility.value = get_label_visibility_proto_value(
label_visibility
)
if help is not None:
time_input_proto.help = dedent(help)
serde = TimeInputSerde(parsed_time)
widget_state = register_widget(
time_input_proto.id,
on_change_handler=on_change,
args=args,
kwargs=kwargs,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="string_value",
)
if widget_state.value_changed:
if (serialized_value := serde.serialize(widget_state.value)) is not None:
time_input_proto.value = serialized_value
time_input_proto.set_value = True
validate_width(width)
layout_config = LayoutConfig(width=width)
self.dg._enqueue("time_input", time_input_proto, layout_config=layout_config)
return widget_state.value
@overload
def datetime_input(
self,
label: str,
value: None,
min_value: DateTimeValue = None,
max_value: DateTimeValue = None,
*, # keyword-only arguments:
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
format: str = "YYYY/MM/DD",
step: int | timedelta = timedelta(minutes=DEFAULT_STEP_MINUTES),
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> datetime | None: ...
@overload
def datetime_input(
self,
label: str,
value: DateTimeScalarValue = "now",
min_value: DateTimeValue = None,
max_value: DateTimeValue = None,
*, # keyword-only arguments:
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
format: str = "YYYY/MM/DD",
step: int | timedelta = timedelta(minutes=DEFAULT_STEP_MINUTES),
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> datetime: ...
@gather_metrics("datetime_input")
def datetime_input(
self,
label: str,
value: DateTimeValue = "now",
min_value: DateTimeValue = None,
max_value: DateTimeValue = None,
*, # keyword-only arguments:
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
format: str = "YYYY/MM/DD",
step: int | timedelta = timedelta(minutes=DEFAULT_STEP_MINUTES),
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> datetime | None:
r"""Display a date and time input widget.
Parameters
----------
label : str
A short label explaining to the user what this datetime input is for.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
For accessibility reasons, you should never set an empty label, but
you can hide it with ``label_visibility`` if needed. In the future,
we may disallow empty labels by raising an exception.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
value : "now", datetime.datetime, datetime.date, datetime.time, str, or None
The value of this widget when it first renders. This can be one of
the following:
- ``"now"`` (default): The widget initializes with the current date and time.
- A ``datetime.datetime`` object: The widget initializes with the given
datetime, stripping any timezone information.
- A ``datetime.date`` object: The widget initializes with the given date
at 00:00.
- A ``datetime.time`` object: The widget initializes with today's date
and the provided time.
- An ISO-formatted datetime (YYYY-MM-DD hh:mm[:ss]) or date/time
string: The widget initializes with the parsed value.
- ``None``: The widget initializes with no value and returns ``None``
until the user selects a datetime.
min_value : "now", datetime.datetime, datetime.date, datetime.time, str, or None
The minimum selectable datetime. This can be any of the datetime
types accepted by ``value``.
If this is ``None`` (default), the minimum selectable datetime is
ten years before the initial value. If no initial value is set, the
minimum selectable datetime is ten years before today at 00:00.
max_value : "now", datetime.datetime, datetime.date, datetime.time, str, or None
The maximum selectable datetime. This can be any of the datetime
types accepted by ``value``.
If this is ``None`` (default), the maximum selectable datetime is
ten years after the initial value. If no initial value is set, the
maximum selectable datetime is ten years after today at 23:59.
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget based on its
content. No two widgets may have the same key.
help : str or None
A tooltip that gets displayed next to the widget label. Streamlit
only displays the tooltip when ``label_visibility="visible"``. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
on_change : callable
An optional callback invoked when this datetime_input's value changes.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
format : str
A format string controlling how the interface displays dates.
Supports ``"YYYY/MM/DD"`` (default), ``"DD/MM/YYYY"``, or ``"MM/DD/YYYY"``.
You may also use a period (.) or hyphen (-) as separators. This
doesn't affect the time format.
step : int or timedelta
The stepping interval in seconds. This defaults to ``900`` (15
minutes). You can also pass a ``datetime.timedelta`` object. The
value must be between 60 seconds and 23 hours.
disabled : bool
An optional boolean that disables the widget if set to ``True``.
The default is ``False``.
label_visibility : "visible", "hidden", or "collapsed"
The visibility of the label. The default is ``"visible"``. If this
is ``"hidden"``, Streamlit displays an empty spacer instead of the
label, which can help keep the widget aligned with other widgets.
If this is ``"collapsed"``, Streamlit displays no label or spacer.
width : "stretch" or int
The width of the widget. This can be one of the following:
- ``"stretch"`` (default): The width of the widget matches the width
of the parent container.
- An integer specifying the width in pixels: The widget has a fixed
width. If the specified width is greater than the width of the
parent container, the widget matches the container width.
Returns
-------
datetime.datetime or None
The current value of the datetime input widget (without timezone)
or ``None`` if no value has been selected.
Examples
--------
**Example 1: Basic usage**
>>> import datetime
>>> import streamlit as st
>>>
>>> event_time = st.datetime_input(
... "Schedule your event",
... datetime.datetime(2025, 11, 19, 16, 45),
... )
>>> st.write("Event scheduled for", event_time)
.. output::
https://doc-datetime-input.streamlit.app/
height: 500px
**Example 2: Empty initial value**
To initialize an empty datetime input, use ``None`` as the value:
>>> import datetime
>>> import streamlit as st
>>>
>>> event_time = st.datetime_input("Schedule your event", value=None)
>>> st.write("Event scheduled for", event_time)
.. output::
https://doc-datetime-input-empty.streamlit.app/
height: 500px
"""
ctx = get_script_run_ctx()
return self._datetime_input(
label=label,
value=value,
min_value=min_value,
max_value=max_value,
key=key,
help=help,
on_change=on_change,
args=args,
kwargs=kwargs,
format=format,
step=step,
disabled=disabled,
label_visibility=label_visibility,
width=width,
ctx=ctx,
)
def _datetime_input(
self,
label: str,
value: DateTimeValue = "now",
min_value: DateTimeValue = None,
max_value: DateTimeValue = None,
*, # keyword-only arguments:
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
format: str = "YYYY/MM/DD",
step: int | timedelta = timedelta(minutes=DEFAULT_STEP_MINUTES),
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
ctx: ScriptRunContext | None = None,
) -> datetime | None:
key = to_key(key)
check_widget_policies(
self.dg,
key,
on_change,
default_value=value if value != "now" else None,
)
maybe_raise_label_warnings(label, label_visibility)
datetime_values = _DateTimeInputValues.from_raw_values(
value=value,
min_value=min_value,
max_value=max_value,
)
default_value = datetime_values.value
min_value_proto = _datetime_to_proto_string(datetime_values.min)
max_value_proto = _datetime_to_proto_string(datetime_values.max)
if isinstance(value, (datetime, date, time)):
value_for_id: Any = (
None
if default_value is None
else _datetime_to_proto_string(default_value)
)
else:
value_for_id = value
element_id = compute_and_register_element_id(
"date_time_input",
user_key=key,
# Ensure stable IDs when the key is provided; whitelist parameters that
# affect the selectable range or formatting.
key_as_main_identity={"min_value", "max_value", "format", "step"},
dg=self.dg,
label=label,
value=value_for_id,
min_value=min_value_proto,
max_value=max_value_proto,
help=help,
format=format,
step=step,
width=width,
)
del value
if not bool(ALLOWED_DATE_FORMATS.match(format)):
raise StreamlitAPIException(
f"The provided format (`{format}`) is not valid. DateTimeInput format "
"should be one of `YYYY/MM/DD`, `DD/MM/YYYY`, or `MM/DD/YYYY` "
"and can also use a period (.) or hyphen (-) as separators."
)
if not isinstance(step, (int, timedelta)):
raise StreamlitAPIException(
f"`step` can only be `int` or `timedelta` but {type(step)} is provided."
)
step_seconds = (
int(step.total_seconds()) if isinstance(step, timedelta) else step
)
if step_seconds < 60 or step_seconds > timedelta(hours=23).seconds:
raise StreamlitAPIException(
f"`step` must be between 60 seconds and 23 hours but is currently set to {step_seconds} seconds."
)
session_state = get_session_state().filtered_state
default_value_for_proto = default_value
if key is not None and key in session_state and session_state[key] is None:
default_value_for_proto = None
date_time_input_proto = DateTimeInputProto()
date_time_input_proto.id = element_id
date_time_input_proto.label = label
if default_value_for_proto is not None:
date_time_input_proto.default[:] = [
_datetime_to_proto_string(default_value_for_proto)
]
date_time_input_proto.min = min_value_proto
date_time_input_proto.max = max_value_proto
date_time_input_proto.form_id = current_form_id(self.dg)
date_time_input_proto.step = step_seconds
date_time_input_proto.disabled = disabled
date_time_input_proto.label_visibility.value = get_label_visibility_proto_value(
label_visibility
)
date_time_input_proto.format = format
date_time_input_proto.is_range = False
if help is not None:
date_time_input_proto.help = dedent(help)
serde = DateTimeInputSerde(
value=default_value_for_proto,
min=datetime_values.min,
max=datetime_values.max,
)
widget_state = register_widget(
date_time_input_proto.id,
on_change_handler=on_change,
args=args,
kwargs=kwargs,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="string_array_value",
)
if widget_state.value_changed:
date_time_input_proto.value[:] = serde.serialize(widget_state.value)
date_time_input_proto.set_value = True
validate_width(width)
layout_config = LayoutConfig(width=width)
self.dg._enqueue(
"date_time_input", date_time_input_proto, layout_config=layout_config
)
return widget_state.value
@overload
def date_input(
self,
label: str,
value: date | datetime | str | Literal["today"] = "today",
min_value: NullableScalarDateValue = None,
max_value: NullableScalarDateValue = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
format: str = "YYYY/MM/DD",
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> date: ...
@overload
def date_input(
self,
label: str,
value: None,
min_value: NullableScalarDateValue = None,
max_value: NullableScalarDateValue = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
format: str = "YYYY/MM/DD",
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> date | None: ...
@overload
def date_input(
self,
label: str,
value: tuple[NullableScalarDateValue]
| tuple[NullableScalarDateValue, NullableScalarDateValue]
| list[NullableScalarDateValue],
min_value: NullableScalarDateValue = None,
max_value: NullableScalarDateValue = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
format: str = "YYYY/MM/DD",
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> DateWidgetRangeReturn: ...
@gather_metrics("date_input")
def date_input(
self,
label: str,
value: DateValue = "today",
min_value: NullableScalarDateValue = None,
max_value: NullableScalarDateValue = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
format: str = "YYYY/MM/DD",
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> DateWidgetReturn:
r"""Display a date input widget.
The date input widget can be configured to accept a single date or a
date range. The first day of the week is determined from the user's
locale in their browser.
Parameters
----------
label : str
A short label explaining to the user what this date input is for.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
For accessibility reasons, you should never set an empty label, but
you can hide it with ``label_visibility`` if needed. In the future,
we may disallow empty labels by raising an exception.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
value : "today", datetime.date, datetime.datetime, str, list/tuple of these, or None
The value of this widget when it first renders. This can be one of
the following:
- ``"today"`` (default): The widget initializes with the current date.
- A ``datetime.date`` or ``datetime.datetime`` object: The widget
initializes with the given date, ignoring any time if included.
- An ISO-formatted date (YYYY-MM-DD) or datetime
(YYYY-MM-DD hh:mm:ss) string: The widget initializes with the
given date, ignoring any time if included.
- A list or tuple with up to two of the above: The widget will
initialize with the given date interval and return a tuple of the
selected interval. You can pass an empty list to initialize the
widget with an empty interval or a list with one value to
initialize only the beginning date of the iterval.
- ``None``: The widget initializes with no date and returns
``None`` until the user selects a date.
min_value : "today", datetime.date, datetime.datetime, str, or None
The minimum selectable date. This can be any of the date types
accepted by ``value``, except list or tuple.
If this is ``None`` (default), the minimum selectable date is ten
years before the initial value. If the initial value is an
interval, the minimum selectable date is ten years before the start
date of the interval. If no initial value is set, the minimum
selectable date is ten years before today.
max_value : "today", datetime.date, datetime.datetime, str, or None
The maximum selectable date. This can be any of the date types
accepted by ``value``, except list or tuple.
If this is ``None`` (default), the maximum selectable date is ten
years after the initial value. If the initial value is an interval,
the maximum selectable date is ten years after the end date of the
interval. If no initial value is set, the maximum selectable date
is ten years after today.
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. No two widgets may have the same key.
help : str or None
A tooltip that gets displayed next to the widget label. Streamlit
only displays the tooltip when ``label_visibility="visible"``. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
on_change : callable
An optional callback invoked when this date_input's value changes.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
format : str
A format string controlling how the interface should display dates.
Supports ``"YYYY/MM/DD"`` (default), ``"DD/MM/YYYY"``, or ``"MM/DD/YYYY"``.
You may also use a period (.) or hyphen (-) as separators.
disabled : bool
An optional boolean that disables the date input if set to
``True``. The default is ``False``.
label_visibility : "visible", "hidden", or "collapsed"
The visibility of the label. The default is ``"visible"``. If this
is ``"hidden"``, Streamlit displays an empty spacer instead of the
label, which can help keep the widget aligned with other widgets.
If this is ``"collapsed"``, Streamlit displays no label or spacer.
width : "stretch" or int
The width of the date input widget. This can be one of the following:
- ``"stretch"`` (default): The width of the widget matches the
width of the parent container.
- An integer specifying the width in pixels: The widget has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the widget matches the width
of the parent container.
Returns
-------
datetime.date or a tuple with 0-2 dates or None
The current value of the date input widget or ``None`` if no date has been
selected.
Examples
--------
**Example 1: Basic usage**
>>> import datetime
>>> import streamlit as st
>>>
>>> d = st.date_input("When's your birthday", datetime.date(2019, 7, 6))
>>> st.write("Your birthday is:", d)
.. output::
https://doc-date-input.streamlit.app/
height: 380px
**Example 2: Date range**
>>> import datetime
>>> import streamlit as st
>>>
>>> today = datetime.datetime.now()
>>> next_year = today.year + 1
>>> jan_1 = datetime.date(next_year, 1, 1)
>>> dec_31 = datetime.date(next_year, 12, 31)
>>>
>>> d = st.date_input(
... "Select your vacation for next year",
... (jan_1, datetime.date(next_year, 1, 7)),
... jan_1,
... dec_31,
... format="MM.DD.YYYY",
... )
>>> d
.. output::
https://doc-date-input1.streamlit.app/
height: 380px
**Example 3: Empty initial value**
To initialize an empty date input, use ``None`` as the value:
>>> import datetime
>>> import streamlit as st
>>>
>>> d = st.date_input("When's your birthday", value=None)
>>> st.write("Your birthday is:", d)
.. output::
https://doc-date-input-empty.streamlit.app/
height: 380px
"""
ctx = get_script_run_ctx()
return self._date_input(
label=label,
value=value,
min_value=min_value,
max_value=max_value,
key=key,
help=help,
on_change=on_change,
args=args,
kwargs=kwargs,
disabled=disabled,
label_visibility=label_visibility,
format=format,
width=width,
ctx=ctx,
)
def _date_input(
self,
label: str,
value: DateValue = "today",
min_value: NullableScalarDateValue = None,
max_value: NullableScalarDateValue = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
format: str = "YYYY/MM/DD",
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
ctx: ScriptRunContext | None = None,
) -> DateWidgetReturn:
key = to_key(key)
check_widget_policies(
self.dg,
key,
on_change,
default_value=value if value != "today" else None,
)
maybe_raise_label_warnings(label, label_visibility)
def parse_date_deterministic_for_id(v: NullableScalarDateValue) -> str | None:
if v == "today":
# For ID purposes, no need to parse the input string.
return None
if isinstance(v, str):
# For ID purposes, no need to parse the input string.
return v
if isinstance(v, datetime):
return date.strftime(v.date(), "%Y/%m/%d")
if isinstance(v, date):
return date.strftime(v, "%Y/%m/%d")
return None
parsed_min_date = parse_date_deterministic_for_id(min_value)
parsed_max_date = parse_date_deterministic_for_id(max_value)
parsed: str | None | list[str | None]
if value == "today":
parsed = None
elif isinstance(value, Sequence):
parsed = [parse_date_deterministic_for_id(v) for v in value]
else:
parsed = parse_date_deterministic_for_id(value)
# TODO: this is missing the error path, integrate with the dateinputvalues parsing
element_id = compute_and_register_element_id(
"date_input",
user_key=key,
# Ensure stable ID when key is provided; explicitly whitelist parameters
# that might invalidate the current widget state.
# format should be supported. However, there is a bug in baseweb where
# changing the format dynamically leads to a wrongly formatted date.
# So, we whitelist it for now until we migrate this away from baseweb.
key_as_main_identity={"min_value", "max_value", "format"},
dg=self.dg,
label=label,
value=parsed,
min_value=parsed_min_date,
max_value=parsed_max_date,
help=help,
format=format,
width=width,
)
if not bool(ALLOWED_DATE_FORMATS.match(format)):
raise StreamlitAPIException(
f"The provided format (`{format}`) is not valid. DateInput format "
"should be one of `YYYY/MM/DD`, `DD/MM/YYYY`, or `MM/DD/YYYY` "
"and can also use a period (.) or hyphen (-) as separators."
)
parsed_values = _DateInputValues.from_raw_values(
value=value,
min_value=min_value,
max_value=max_value,
)
if value == "today":
# We need to know if this is a single or range date_input, but don't have
# a default value, so we check if session_state can tell us.
# We already calculated the id, so there is no risk of this causing
# the id to change.
session_state = get_session_state().filtered_state
if key is not None and key in session_state:
state_value = session_state[key]
parsed_values = _DateInputValues.from_raw_values(
value=state_value,
min_value=min_value,
max_value=max_value,
)
del value, min_value, max_value
date_input_proto = DateInputProto()
date_input_proto.id = element_id
date_input_proto.is_range = parsed_values.is_range
date_input_proto.disabled = disabled
date_input_proto.label_visibility.value = get_label_visibility_proto_value(
label_visibility
)
date_input_proto.format = format
date_input_proto.label = label
if parsed_values.value is None:
# An empty array represents the empty state. The reason for using an empty
# array here is that we cannot optional keyword for repeated fields
# in protobuf.
date_input_proto.default[:] = []
else:
date_input_proto.default[:] = [
date.strftime(v, "%Y/%m/%d") for v in parsed_values.value
]
date_input_proto.min = date.strftime(parsed_values.min, "%Y/%m/%d")
date_input_proto.max = date.strftime(parsed_values.max, "%Y/%m/%d")
date_input_proto.form_id = current_form_id(self.dg)
if help is not None:
date_input_proto.help = dedent(help)
serde = DateInputSerde(parsed_values)
widget_state = register_widget(
date_input_proto.id,
on_change_handler=on_change,
args=args,
kwargs=kwargs,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="string_array_value",
)
if widget_state.value_changed:
date_input_proto.value[:] = serde.serialize(widget_state.value)
date_input_proto.set_value = True
validate_width(width)
layout_config = LayoutConfig(width=width)
self.dg._enqueue("date_input", date_input_proto, layout_config=layout_config)
return widget_state.value
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/widgets/data_editor.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import json
from dataclasses import dataclass
from decimal import Decimal
from typing import (
TYPE_CHECKING,
Any,
Final,
Literal,
TypeAlias,
TypedDict,
TypeVar,
Union,
cast,
overload,
)
from typing_extensions import Required
from streamlit import dataframe_util
from streamlit import logger as _logger
from streamlit.deprecation_util import (
make_deprecated_name_warning,
show_deprecation_warning,
)
from streamlit.elements.lib.column_config_utils import (
INDEX_IDENTIFIER,
ColumnConfigMapping,
ColumnConfigMappingInput,
ColumnDataKind,
DataframeSchema,
apply_data_specific_configs,
determine_dataframe_schema,
is_type_compatible,
marshall_column_config,
process_config_mapping,
update_column_config,
)
from streamlit.elements.lib.form_utils import current_form_id
from streamlit.elements.lib.layout_utils import (
Height,
LayoutConfig,
Width,
validate_height,
validate_width,
)
from streamlit.elements.lib.pandas_styler_utils import marshall_styler
from streamlit.elements.lib.policies import check_widget_policies
from streamlit.elements.lib.utils import Key, compute_and_register_element_id, to_key
from streamlit.errors import StreamlitAPIException
from streamlit.proto.Arrow_pb2 import Arrow as ArrowProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner_utils.script_run_context import get_script_run_ctx
from streamlit.runtime.state import (
WidgetArgs,
WidgetCallback,
WidgetKwargs,
register_widget,
)
from streamlit.type_util import is_list_like, is_type
from streamlit.util import calc_md5
if TYPE_CHECKING:
from collections.abc import Iterable, Mapping
import numpy as np
import pandas as pd
import pyarrow as pa
from pandas.io.formats.style import Styler
from streamlit.delta_generator import DeltaGenerator
_LOGGER: Final = _logger.get_logger(__name__)
# All formats that support direct editing, meaning that these
# formats will be returned with the same type when used with data_editor.
EditableData = TypeVar(
"EditableData",
bound=dataframe_util.DataFrameGenericAlias[Any]
| tuple[Any]
| list[Any]
| set[Any]
| dict[str, Any],
)
# All data types supported by the data editor.
DataTypes: TypeAlias = Union[
"pd.DataFrame",
"pd.Series[Any]",
"pd.Index[Any]",
"Styler",
"pa.Table",
"np.ndarray[Any, np.dtype[np.float64]]",
tuple[Any],
list[Any],
set[Any],
dict[str, Any],
]
class EditingState(TypedDict, total=False):
"""
A dictionary representing the current state of the data editor.
Attributes
----------
edited_rows : Dict[int, Dict[str, str | int | float | bool | None]]
An hierarchical mapping of edited cells based on:
row position -> column name -> value.
added_rows : List[Dict[str, str | int | float | bool | None]]
A list of added rows, where each row is a mapping from column name to
the cell value.
deleted_rows : List[int]
A list of deleted rows, where each row is the numerical position of
the deleted row.
"""
edited_rows: Required[dict[int, dict[str, str | int | float | bool | None]]]
added_rows: Required[list[dict[str, str | int | float | bool | None]]]
deleted_rows: Required[list[int]]
@dataclass
class DataEditorSerde:
"""DataEditorSerde is used to serialize and deserialize the data editor state."""
def deserialize(self, ui_value: str | None) -> EditingState:
data_editor_state: EditingState = cast(
"EditingState",
{
"edited_rows": {},
"added_rows": [],
"deleted_rows": [],
}
if ui_value is None
else json.loads(ui_value),
)
# Make sure that all editing state keys are present:
if "edited_rows" not in data_editor_state:
data_editor_state["edited_rows"] = {} # type: ignore[unreachable]
if "deleted_rows" not in data_editor_state:
data_editor_state["deleted_rows"] = [] # type: ignore[unreachable]
if "added_rows" not in data_editor_state:
data_editor_state["added_rows"] = [] # type: ignore[unreachable]
# Convert the keys (numerical row positions) to integers.
# The keys are strings because they are serialized to JSON.
data_editor_state["edited_rows"] = {
int(k): v
for k, v in data_editor_state["edited_rows"].items() # ty: ignore[possibly-missing-attribute]
}
return data_editor_state
def serialize(self, editing_state: EditingState) -> str:
return json.dumps(editing_state, default=str)
def _parse_value(
value: str | int | float | bool | list[str] | None,
column_data_kind: ColumnDataKind,
) -> Any:
"""Convert a value to the correct type.
Parameters
----------
value : str | int | float | bool | list[str] | None
The value to convert.
column_data_kind : ColumnDataKind
The determined data kind of the column. The column data kind refers to the
shared data type of the values in the column (e.g. int, float, str).
Returns
-------
The converted value.
"""
if value is None:
return None
import pandas as pd
try:
if column_data_kind in (ColumnDataKind.LIST, ColumnDataKind.EMPTY):
return list(value) if is_list_like(value) else [value] # ty: ignore
if column_data_kind == ColumnDataKind.STRING:
return str(value)
# List values aren't supported for anything else than list column data kind.
# To make the type checker happy, we raise a TypeError here. However,
# This isn't expected to happen.
if isinstance(value, list):
raise TypeError( # noqa: TRY301
"List values are only supported by list, string and empty columns."
)
if column_data_kind == ColumnDataKind.INTEGER:
return int(value)
if column_data_kind == ColumnDataKind.FLOAT:
return float(value)
if column_data_kind == ColumnDataKind.BOOLEAN:
return bool(value)
if column_data_kind == ColumnDataKind.DECIMAL:
# Decimal theoretically can also be initialized via number values.
# However, using number values here seems to cause issues with Arrow
# serialization, once you try to render the returned dataframe.
return Decimal(str(value))
if column_data_kind == ColumnDataKind.TIMEDELTA:
return pd.Timedelta(value)
if column_data_kind in [
ColumnDataKind.DATETIME,
ColumnDataKind.DATE,
ColumnDataKind.TIME,
]:
datetime_value = pd.Timestamp(value) # ty: ignore
if pd.isna(datetime_value):
return None # type: ignore[unreachable]
if column_data_kind == ColumnDataKind.DATETIME:
return datetime_value
if column_data_kind == ColumnDataKind.DATE:
return datetime_value.date()
if column_data_kind == ColumnDataKind.TIME:
return datetime_value.time()
except (ValueError, pd.errors.ParserError, TypeError) as ex:
_LOGGER.warning(
"Failed to parse value %s as %s.",
value,
column_data_kind,
exc_info=ex,
)
return None
return value
def _apply_cell_edits(
df: pd.DataFrame,
edited_rows: Mapping[
int, Mapping[str, str | int | float | bool | list[str] | None]
],
dataframe_schema: DataframeSchema,
) -> None:
"""Apply cell edits to the provided dataframe (inplace).
Parameters
----------
df : pd.DataFrame
The dataframe to apply the cell edits to.
edited_rows : Mapping[int, Mapping[str, str | int | float | bool | None]]
A hierarchical mapping based on row position -> column name -> value
dataframe_schema: DataframeSchema
The schema of the dataframe.
"""
for row_id, row_changes in edited_rows.items():
row_pos = int(row_id)
for col_name, value in row_changes.items():
if col_name == INDEX_IDENTIFIER:
# The edited cell is part of the index
# TODO(lukasmasuch): To support multi-index in the future:
# use a tuple of values here instead of a single value
old_idx_value = df.index[row_pos]
new_idx_value = _parse_value(value, dataframe_schema[INDEX_IDENTIFIER])
df.rename(
index={old_idx_value: new_idx_value},
inplace=True, # noqa: PD002
)
else:
col_pos = df.columns.get_loc(col_name)
df.iat[row_pos, col_pos] = _parse_value( # type: ignore
value, dataframe_schema[col_name]
)
def _parse_added_row(
df: pd.DataFrame,
added_row: dict[str, Any],
dataframe_schema: DataframeSchema,
) -> tuple[Any, list[Any]]:
"""Parse the added row into an optional index value and a list of row values."""
index_value = None
new_row: list[Any] = [None for _ in range(df.shape[1])]
for col_name, value in added_row.items():
if col_name == INDEX_IDENTIFIER:
# TODO(lukasmasuch): To support multi-index in the future:
# use a tuple of values here instead of a single value
index_value = _parse_value(value, dataframe_schema[INDEX_IDENTIFIER])
else:
col_pos = cast("int", df.columns.get_loc(col_name))
new_row[col_pos] = _parse_value(value, dataframe_schema[col_name])
return index_value, new_row
def _assign_row_values(
df: pd.DataFrame,
row_label: Any,
row_values: list[Any],
) -> None:
"""Assign values to a dataframe row via a mapping.
This avoids numpy attempting to coerce nested sequences (e.g. lists) into
multi-dimensional arrays when a column legitimately stores list values.
"""
df.loc[row_label] = dict(zip(df.columns, row_values, strict=True))
def _apply_row_additions(
df: pd.DataFrame,
added_rows: list[dict[str, Any]],
dataframe_schema: DataframeSchema,
) -> None:
"""Apply row additions to the provided dataframe (inplace).
Parameters
----------
df : pd.DataFrame
The dataframe to apply the row additions to.
added_rows : List[Dict[str, Any]]
A list of row additions. Each row addition is a dictionary with the
column position as key and the new cell value as value.
dataframe_schema: DataframeSchema
The schema of the dataframe.
"""
if not added_rows:
return
import pandas as pd
index_type: Literal["range", "integer", "other"] = "other"
# This is only used if the dataframe has a range or integer index that can be
# auto incremented:
index_stop: int | None = None
index_step: int | None = None
if isinstance(df.index, pd.RangeIndex):
# Extract metadata from the range index:
index_type = "range"
index_stop = df.index.stop
index_step = df.index.step
elif isinstance(df.index, pd.Index) and pd.api.types.is_integer_dtype(
df.index.dtype
):
# Get highest integer value and increment it by 1 to get unique index value.
index_type = "integer"
index_stop = 0 if df.index.empty else df.index.max() + 1
index_step = 1
for added_row in added_rows:
index_value, new_row = _parse_added_row(df, added_row, dataframe_schema)
if index_value is not None and index_type != "range":
# Case 1: Non-range index with an explicitly provided index value
# Add row using the user-provided index value.
# This handles any type of index that cannot be auto incremented.
# Note: this just overwrites the row in case the index value
# already exists. In the future, it would be better to
# require users to provide unique non-None values for the index with
# some kind of visual indications.
_assign_row_values(df, index_value, new_row)
continue
if index_stop is not None and index_step is not None:
# Case 2: Range or integer index that can be auto incremented.
# Add row using the next value in the sequence
_assign_row_values(df, index_stop, new_row)
# Increment to the next range index value
index_stop += index_step
continue
# Row cannot be added -> skip it and log a warning.
_LOGGER.warning(
"Cannot automatically add row for the index "
"of type %s without an explicit index value. Row addition skipped.",
type(df.index).__name__,
)
def _apply_row_deletions(df: pd.DataFrame, deleted_rows: list[int]) -> None:
"""Apply row deletions to the provided dataframe (inplace).
Parameters
----------
df : pd.DataFrame
The dataframe to apply the row deletions to.
deleted_rows : List[int]
A list of row numbers to delete.
"""
# Drop rows based in numeric row positions
df.drop(df.index[deleted_rows], inplace=True) # noqa: PD002
def _apply_dataframe_edits(
df: pd.DataFrame,
data_editor_state: EditingState,
dataframe_schema: DataframeSchema,
) -> None:
"""Apply edits to the provided dataframe (inplace).
This includes cell edits, row additions and row deletions.
Parameters
----------
df : pd.DataFrame
The dataframe to apply the edits to.
data_editor_state : EditingState
The editing state of the data editor component.
dataframe_schema: DataframeSchema
The schema of the dataframe.
"""
if data_editor_state.get("edited_rows"):
_apply_cell_edits(df, data_editor_state["edited_rows"], dataframe_schema)
if data_editor_state.get("deleted_rows"):
_apply_row_deletions(df, data_editor_state["deleted_rows"])
if data_editor_state.get("added_rows"):
# The addition of new rows needs to happen after the deletion to not have
# unexpected side-effects, like https://github.com/streamlit/streamlit/issues/8854
_apply_row_additions(df, data_editor_state["added_rows"], dataframe_schema)
def _is_supported_index(df_index: pd.Index[Any]) -> bool:
"""Check if the index is supported by the data editor component.
Parameters
----------
df_index : pd.Index
The index to check.
Returns
-------
bool
True if the index is supported, False otherwise.
"""
import pandas as pd
return (
type(df_index)
in [
pd.RangeIndex,
pd.Index,
pd.DatetimeIndex,
pd.CategoricalIndex,
# Interval type isn't editable currently:
# pd.IntervalIndex,
# Period type isn't editable currently:
# pd.PeriodIndex,
]
# We need to check these index types without importing, since they are
# deprecated and planned to be removed soon.
or is_type(df_index, "pandas.core.indexes.numeric.Int64Index")
or is_type(df_index, "pandas.core.indexes.numeric.Float64Index")
or is_type(df_index, "pandas.core.indexes.numeric.UInt64Index")
)
def _fix_column_headers(data_df: pd.DataFrame) -> None:
"""Fix the column headers of the provided dataframe inplace to work
correctly for data editing.
"""
import pandas as pd
if isinstance(data_df.columns, pd.MultiIndex):
# Flatten hierarchical column headers to a single level:
data_df.columns = [
"_".join(map(str, header)) for header in data_df.columns.to_flat_index()
]
elif pd.api.types.infer_dtype(data_df.columns) != "string":
# If the column names are not all strings, we need to convert them to strings
# to avoid issues with editing:
data_df.rename(
columns={column: str(column) for column in data_df.columns},
inplace=True, # noqa: PD002
)
def _check_column_names(data_df: pd.DataFrame) -> None:
"""Check if the column names in the provided dataframe are valid.
It's not allowed to have duplicate column names or column names that are
named ``_index``. If the column names are not valid, a ``StreamlitAPIException``
is raised.
"""
if data_df.columns.empty:
return
# Check if the column names are unique and raise an exception if not.
# Add the names of the duplicated columns to the exception message.
duplicated_columns = data_df.columns[data_df.columns.duplicated()]
if len(duplicated_columns) > 0:
raise StreamlitAPIException(
f"All column names are required to be unique for usage with data editor. "
f"The following column names are duplicated: {list(duplicated_columns)}. "
f"Please rename the duplicated columns in the provided data."
)
# Check if the column names are not named "_index" and raise an exception if so.
if INDEX_IDENTIFIER in data_df.columns:
raise StreamlitAPIException(
f"The column name '{INDEX_IDENTIFIER}' is reserved for the index column "
f"and can't be used for data columns. Please rename the column in the "
f"provided data."
)
def _check_type_compatibilities(
data_df: pd.DataFrame,
columns_config: ColumnConfigMapping,
dataframe_schema: DataframeSchema,
) -> None:
"""Check column type to data type compatibility.
Iterates the index and all columns of the dataframe to check if
the configured column types are compatible with the underlying data types.
Parameters
----------
data_df : pd.DataFrame
The dataframe to check the type compatibilities for.
columns_config : ColumnConfigMapping
A mapping of column to column configurations.
dataframe_schema : DataframeSchema
The schema of the dataframe.
Raises
------
StreamlitAPIException
If a configured column type is editable and not compatible with the
underlying data type.
"""
# TODO(lukasmasuch): Update this here to support multi-index in the future:
indices = [(INDEX_IDENTIFIER, data_df.index)]
for column in indices + list(data_df.items()):
column_name = str(column[0])
column_data_kind = dataframe_schema[column_name]
# TODO(lukasmasuch): support column config via numerical index here?
if column_name in columns_config:
column_config = columns_config[column_name]
if column_config.get("disabled") is True:
# Disabled columns are not checked for compatibility.
# This might change in the future.
continue
type_config = column_config.get("type_config")
if type_config is None:
continue
configured_column_type = type_config.get("type")
if configured_column_type is None:
# Just a safeguard, is not expected to happen.
continue # type: ignore[unreachable]
if is_type_compatible(configured_column_type, column_data_kind) is False:
raise StreamlitAPIException(
f"The configured column type `{configured_column_type}` for column "
f"`{column_name}` is not compatible for editing the underlying "
f"data type `{column_data_kind}`.\n\nYou have following options to "
f"fix this: 1) choose a compatible type 2) disable the column "
f"3) convert the column into a compatible data type."
)
class DataEditorMixin:
@overload
def data_editor(
self,
data: EditableData,
*,
width: Width = "stretch",
height: Height | Literal["auto"] = "auto",
use_container_width: bool | None = None,
hide_index: bool | None = None,
column_order: Iterable[str] | None = None,
column_config: ColumnConfigMappingInput | None = None,
num_rows: Literal["fixed", "dynamic"] = "fixed",
disabled: bool | Iterable[str | int] = False,
key: Key | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
row_height: int | None = None,
placeholder: str | None = None,
) -> EditableData:
pass
@overload
def data_editor(
self,
data: Any,
*,
width: Width = "stretch",
height: Height | Literal["auto"] = "auto",
use_container_width: bool | None = None,
hide_index: bool | None = None,
column_order: Iterable[str] | None = None,
column_config: ColumnConfigMappingInput | None = None,
num_rows: Literal["fixed", "dynamic"] = "fixed",
disabled: bool | Iterable[str | int] = False,
key: Key | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
row_height: int | None = None,
placeholder: str | None = None,
) -> pd.DataFrame:
pass
@gather_metrics("data_editor")
def data_editor(
self,
data: DataTypes,
*,
width: Width = "stretch",
height: Height | Literal["auto"] = "auto",
use_container_width: bool | None = None,
hide_index: bool | None = None,
column_order: Iterable[str] | None = None,
column_config: ColumnConfigMappingInput | None = None,
num_rows: Literal["fixed", "dynamic"] = "fixed",
disabled: bool | Iterable[str | int] = False,
key: Key | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
row_height: int | None = None,
placeholder: str | None = None,
) -> DataTypes:
"""Display a data editor widget.
The data editor widget allows you to edit dataframes and many other data structures in a table-like UI.
Parameters
----------
data : Anything supported by st.dataframe
The data to edit in the data editor.
.. note::
- Styles from ``pandas.Styler`` will only be applied to non-editable columns.
- Text and number formatting from ``column_config`` always takes
precedence over text and number formatting from ``pandas.Styler``.
- If your dataframe starts with an empty column, you should set
the column datatype in the underlying dataframe to ensure your
intended datatype, especially for integers versus floats.
- Mixing data types within a column can make the column uneditable.
- Additionally, the following data types are not yet supported for editing:
``complex``, ``tuple``, ``bytes``, ``bytearray``,
``memoryview``, ``dict``, ``set``, ``frozenset``,
``fractions.Fraction``, ``pandas.Interval``, and
``pandas.Period``.
- To prevent overflow in JavaScript, columns containing
``datetime.timedelta`` and ``pandas.Timedelta`` values will
default to uneditable, but this can be changed through column
configuration.
width : "stretch", "content", or int
The width of the data editor. This can be one of the following:
- ``"stretch"`` (default): The width of the editor matches the
width of the parent container.
- ``"content"``: The width of the editor matches the width of its
content, but doesn't exceed the width of the parent container.
- An integer specifying the width in pixels: The editor has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the editor matches the width
of the parent container.
height : "auto", "content", "stretch", or int
The height of the data editor. This can be one of the following:
- ``"auto"`` (default): Streamlit sets the height to show at most
ten rows.
- ``"content"``: The height of the editor matches the height of
its content. The height is capped at 10,000 pixels to prevent
performance issues with very large dataframes.
- ``"stretch"``: The height of the editor expands to fill the
available vertical space in its parent container. When multiple
elements with stretch height are in the same container, they
share the available vertical space evenly. The editor will
maintain a minimum height to display up to three rows, but
otherwise won't exceed the available height in its parent
container.
- An integer specifying the height in pixels: The editor has a
fixed height.
Vertical scrolling within the editor is enabled when the height
does not accommodate all rows.
use_container_width : bool
Whether to override ``width`` with the width of the parent
container. If this is ``True`` (default), Streamlit sets the width
of the data editor to match the width of the parent container. If
this is ``False``, Streamlit sets the data editor's width according
to ``width``.
.. deprecated::
``use_container_width`` is deprecated and will be removed in a
future release. For ``use_container_width=True``, use
``width="stretch"``.
hide_index : bool or None
Whether to hide the index column(s). If ``hide_index`` is ``None``
(default), the visibility of index columns is automatically
determined based on the data.
column_order : Iterable[str] or None
The ordered list of columns to display. If this is ``None``
(default), Streamlit displays all columns in the order inherited
from the underlying data structure. If this is a list, the
indicated columns will display in the order they appear within the
list. Columns may be omitted or repeated within the list.
For example, ``column_order=("col2", "col1")`` will display
``"col2"`` first, followed by ``"col1"``, and will hide all other
non-index columns.
``column_order`` does not accept positional column indices and
can't move the index column(s).
column_config : dict or None
Configuration to customize how columns are displayed. If this is
``None`` (default), columns are styled based on the underlying data
type of each column.
Column configuration can modify column names, visibility, type,
width, format, editing properties like min/max, and more. If this
is a dictionary, the keys are column names (strings) and/or
positional column indices (integers), and the values are one of the
following:
- ``None`` to hide the column.
- A string to set the display label of the column.
- One of the column types defined under ``st.column_config``. For
example, to show a column as dollar amounts, use
``st.column_config.NumberColumn("Dollar values", format="$ %d")``.
See more info on the available column types and config options
`here <https://docs.streamlit.io/develop/api-reference/data/st.column_config>`_.
To configure the index column(s), use ``"_index"`` as the column
name, or use a positional column index where ``0`` refers to the
first index column.
num_rows : "fixed" or "dynamic"
Specifies if the user can add and delete rows in the data editor.
If "fixed", the user cannot add or delete rows. If "dynamic", the user can
add and delete rows in the data editor, but column sorting is disabled.
Defaults to "fixed".
disabled : bool or Iterable[str | int]
Controls the editing of columns. This can be one of the following:
- ``False`` (default): All columns that support editing are editable.
- ``True``: All columns are disabled for editing.
- An Iterable of column names and/or positional indices: The
specified columns are disabled for editing while the remaining
columns are editable where supported. For example,
``disabled=["col1", "col2"]`` will disable editing for the
columns named "col1" and "col2".
To disable editing for the index column(s), use ``"_index"`` as the
column name, or use a positional column index where ``0`` refers to
the first index column.
key : str
An optional string to use as the unique key for this widget. If this
is omitted, a key will be generated for the widget based on its
content. No two widgets may have the same key.
on_change : callable
An optional callback invoked when this data_editor's value changes.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
row_height : int or None
The height of each row in the data editor in pixels. If ``row_height``
is ``None`` (default), Streamlit will use a default row height,
which fits one line of text.
placeholder : str or None
The text that should be shown for missing values. If this is
``None`` (default), missing values are displayed as "None". To
leave a cell empty, use an empty string (``""``). Other common
values are ``"null"``, ``"NaN"`` and ``"-"``.
Returns
-------
pandas.DataFrame, pandas.Series, pyarrow.Table, numpy.ndarray, list, set, tuple, or dict.
The edited data. The edited data is returned in its original data type if
it corresponds to any of the supported return types. All other data types
are returned as a ``pandas.DataFrame``.
Examples
--------
**Example 1: Basic usage**
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> df = pd.DataFrame(
>>> [
>>> {"command": "st.selectbox", "rating": 4, "is_widget": True},
>>> {"command": "st.balloons", "rating": 5, "is_widget": False},
>>> {"command": "st.time_input", "rating": 3, "is_widget": True},
>>> ]
>>> )
>>> edited_df = st.data_editor(df)
>>>
>>> favorite_command = edited_df.loc[edited_df["rating"].idxmax()]["command"]
>>> st.markdown(f"Your favorite command is **{favorite_command}** 🎈")
.. output::
https://doc-data-editor.streamlit.app/
height: 350px
**Example 2: Allowing users to add and delete rows**
You can allow your users to add and delete rows by setting ``num_rows``
to "dynamic":
>>> import streamlit as st
>>> import pandas as pd
>>>
>>> df = pd.DataFrame(
>>> [
>>> {"command": "st.selectbox", "rating": 4, "is_widget": True},
>>> {"command": "st.balloons", "rating": 5, "is_widget": False},
>>> {"command": "st.time_input", "rating": 3, "is_widget": True},
>>> ]
>>> )
>>> edited_df = st.data_editor(df, num_rows="dynamic")
>>>
>>> favorite_command = edited_df.loc[edited_df["rating"].idxmax()]["command"]
>>> st.markdown(f"Your favorite command is **{favorite_command}** 🎈")
.. output::
https://doc-data-editor1.streamlit.app/
height: 450px
**Example 3: Data editor configuration**
You can customize the data editor via ``column_config``, ``hide_index``,
``column_order``, or ``disabled``:
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> df = pd.DataFrame(
>>> [
>>> {"command": "st.selectbox", "rating": 4, "is_widget": True},
>>> {"command": "st.balloons", "rating": 5, "is_widget": False},
>>> {"command": "st.time_input", "rating": 3, "is_widget": True},
>>> ]
>>> )
>>> edited_df = st.data_editor(
>>> df,
>>> column_config={
>>> "command": "Streamlit Command",
>>> "rating": st.column_config.NumberColumn(
>>> "Your rating",
>>> help="How much do you like this command (1-5)?",
>>> min_value=1,
>>> max_value=5,
>>> step=1,
>>> format="%d ⭐",
>>> ),
>>> "is_widget": "Widget ?",
>>> },
>>> disabled=["command", "is_widget"],
>>> hide_index=True,
>>> )
>>>
>>> favorite_command = edited_df.loc[edited_df["rating"].idxmax()]["command"]
>>> st.markdown(f"Your favorite command is **{favorite_command}** 🎈")
.. output::
https://doc-data-editor-config.streamlit.app/
height: 350px
"""
# Lazy-loaded import
import pandas as pd
import pyarrow as pa
key = to_key(key)
validate_width(width, allow_content=True)
validate_height(
height,
allow_content=True,
allow_stretch=True,
additional_allowed=["auto"],
)
check_widget_policies(
self.dg,
key,
on_change,
default_value=None,
writes_allowed=False,
)
if use_container_width is not None:
show_deprecation_warning(
make_deprecated_name_warning(
"use_container_width",
"width",
"2025-12-31",
"For `use_container_width=True`, use `width='stretch'`. "
"For `use_container_width=False`, use `width='content'`.",
include_st_prefix=False,
),
show_in_browser=False,
)
if use_container_width:
width = "stretch"
elif not isinstance(width, int):
width = "content"
if column_order is not None:
column_order = list(column_order)
column_config_mapping: ColumnConfigMapping = {}
data_format = dataframe_util.determine_data_format(data)
if data_format == dataframe_util.DataFormat.UNKNOWN:
raise StreamlitAPIException(
f"The data type ({type(data).__name__}) or format is not supported by "
"the data editor. Please convert your data into a Pandas Dataframe or "
"another supported data format."
)
# The dataframe should always be a copy of the original data
# since we will apply edits directly to it.
data_df = dataframe_util.convert_anything_to_pandas_df(data, ensure_copy=True)
# Check if the index is supported.
if not _is_supported_index(data_df.index):
raise StreamlitAPIException(
f"The type of the dataframe index - {type(data_df.index).__name__} - is not "
"yet supported by the data editor."
)
# Check if the column names are valid and unique.
_check_column_names(data_df)
# Convert the user provided column config into the frontend compatible format:
column_config_mapping = process_config_mapping(column_config)
# Deactivate editing for columns that are not compatible with arrow
for column_name, column_data in data_df.items():
if dataframe_util.is_colum_type_arrow_incompatible(column_data):
update_column_config(
column_config_mapping, str(column_name), {"disabled": True}
)
# Convert incompatible type to string
data_df[cast("Any", column_name)] = column_data.astype("string")
apply_data_specific_configs(column_config_mapping, data_format)
# Fix the column headers to work correctly for data editing:
_fix_column_headers(data_df)
has_range_index = isinstance(data_df.index, pd.RangeIndex)
if not has_range_index:
# If the index is not a range index, we will configure it as required
# since the user is required to provide a (unique) value for editing.
update_column_config(
column_config_mapping, INDEX_IDENTIFIER, {"required": True}
)
if num_rows == "dynamic" and hide_index is True:
_LOGGER.warning(
"Setting `hide_index=True` in data editor with a non-range index will not have any effect "
"when `num_rows='dynamic'`. It is required for the user to fill in index values for "
"adding new rows. To hide the index, make sure to set the DataFrame "
"index to a range index."
)
if hide_index is None and has_range_index and num_rows == "dynamic":
# Temporary workaround:
# We hide range indices if num_rows is dynamic.
# since the current way of handling this index during editing is a
# bit confusing. The user can still decide to show the index by
# setting hide_index explicitly to False.
hide_index = True
if hide_index is not None:
update_column_config(
column_config_mapping, INDEX_IDENTIFIER, {"hidden": hide_index}
)
# If disabled not a boolean, we assume it is a list of columns to disable.
# This gets translated into the columns configuration:
if not isinstance(disabled, bool):
for column in disabled:
update_column_config(column_config_mapping, column, {"disabled": True})
# Convert the dataframe to an arrow table which is used as the main
# serialization format for sending the data to the frontend.
# We also utilize the arrow schema to determine the data kinds of every column.
arrow_table = pa.Table.from_pandas(data_df)
# Determine the dataframe schema which is required for parsing edited values
# and for checking type compatibilities.
dataframe_schema = determine_dataframe_schema(data_df, arrow_table.schema)
# Check if all configured column types are compatible with the underlying data.
# Throws an exception if any of the configured types are incompatible.
_check_type_compatibilities(data_df, column_config_mapping, dataframe_schema)
arrow_bytes = dataframe_util.convert_arrow_table_to_arrow_bytes(arrow_table)
# We want to do this as early as possible to avoid introducing nondeterminism,
# but it isn't clear how much processing is needed to have the data in a
# format that will hash consistently, so we do it late here to have it
# as close as possible to how it used to be.
ctx = get_script_run_ctx()
element_id = compute_and_register_element_id(
"data_editor",
user_key=key,
key_as_main_identity=False,
dg=self.dg,
data=arrow_bytes,
width=width,
height=height,
use_container_width=use_container_width,
column_order=column_order,
column_config_mapping=str(column_config_mapping),
num_rows=num_rows,
row_height=row_height,
placeholder=placeholder,
)
proto = ArrowProto()
proto.id = element_id
if row_height:
proto.row_height = row_height
if column_order:
proto.column_order[:] = column_order
if placeholder is not None:
proto.placeholder = placeholder
# Only set disabled to true if it is actually true
# It can also be a list of columns, which should result in false here.
proto.disabled = disabled is True
proto.editing_mode = (
ArrowProto.EditingMode.DYNAMIC
if num_rows == "dynamic"
else ArrowProto.EditingMode.FIXED
)
proto.form_id = current_form_id(self.dg)
if dataframe_util.is_pandas_styler(data):
# Pandas styler will only work for non-editable/disabled columns.
# Get first 10 chars of md5 hash of the key or delta path as styler uuid
# and set it as styler uuid.
# We are only using the first 10 chars to keep the uuid short since
# it will be used for all the cells in the dataframe. Therefore, this
# might have a significant impact on the message size. 10 chars
# should be good enough to avoid potential collisions in this case.
# Even on collisions, there should not be a big issue with the
# rendering in the data editor.
styler_uuid = calc_md5(key or self.dg._get_delta_path_str())[:10]
data.set_uuid(styler_uuid)
marshall_styler(proto, data, styler_uuid)
proto.data = arrow_bytes
marshall_column_config(proto, column_config_mapping)
# Create layout configuration
# For height, only include it in LayoutConfig if it's not "auto"
# "auto" is the default behavior and doesn't need to be sent
layout_config = LayoutConfig(
width=width, height=height if height != "auto" else None
)
serde = DataEditorSerde()
widget_state = register_widget(
proto.id,
on_change_handler=on_change,
args=args,
kwargs=kwargs,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="string_value",
)
_apply_dataframe_edits(data_df, widget_state.value, dataframe_schema)
self.dg._enqueue("arrow_data_frame", proto, layout_config=layout_config)
return dataframe_util.convert_pandas_df_to_data_format(data_df, data_format)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/widgets/text_widgets.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from dataclasses import dataclass
from textwrap import dedent
from typing import TYPE_CHECKING, Literal, cast, overload
from streamlit.elements.lib.form_utils import current_form_id
from streamlit.elements.lib.layout_utils import (
Height,
LayoutConfig,
WidthWithoutContent,
validate_height,
validate_width,
)
from streamlit.elements.lib.policies import (
check_widget_policies,
maybe_raise_label_warnings,
)
from streamlit.elements.lib.utils import (
Key,
LabelVisibility,
compute_and_register_element_id,
get_label_visibility_proto_value,
to_key,
)
from streamlit.errors import StreamlitAPIException
from streamlit.proto.TextArea_pb2 import TextArea as TextAreaProto
from streamlit.proto.TextInput_pb2 import TextInput as TextInputProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner import ScriptRunContext, get_script_run_ctx
from streamlit.runtime.state import (
WidgetArgs,
WidgetCallback,
WidgetKwargs,
get_session_state,
register_widget,
)
from streamlit.string_util import validate_icon_or_emoji
from streamlit.type_util import SupportsStr
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
from streamlit.type_util import SupportsStr
@dataclass
class TextInputSerde:
value: str | None
def deserialize(self, ui_value: str | None) -> str | None:
return ui_value if ui_value is not None else self.value
def serialize(self, v: str | None) -> str | None:
return v
@dataclass
class TextAreaSerde:
value: str | None
def deserialize(self, ui_value: str | None) -> str | None:
return ui_value if ui_value is not None else self.value
def serialize(self, v: str | None) -> str | None:
return v
class TextWidgetsMixin:
@overload
def text_input(
self,
label: str,
value: str = "",
max_chars: int | None = None,
key: Key | None = None,
type: Literal["default", "password"] = "default",
help: str | None = None,
autocomplete: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
icon: str | None = None,
width: WidthWithoutContent = "stretch",
) -> str:
pass
@overload
def text_input(
self,
label: str,
value: SupportsStr | None = None,
max_chars: int | None = None,
key: Key | None = None,
type: Literal["default", "password"] = "default",
help: str | None = None,
autocomplete: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
icon: str | None = None,
width: WidthWithoutContent = "stretch",
) -> str | None:
pass
@gather_metrics("text_input")
def text_input(
self,
label: str,
value: str | SupportsStr | None = "",
max_chars: int | None = None,
key: Key | None = None,
type: Literal["default", "password"] = "default",
help: str | None = None,
autocomplete: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
icon: str | None = None,
width: WidthWithoutContent = "stretch",
) -> str | None:
r"""Display a single-line text input widget.
Parameters
----------
label : str
A short label explaining to the user what this input is for.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
For accessibility reasons, you should never set an empty label, but
you can hide it with ``label_visibility`` if needed. In the future,
we may disallow empty labels by raising an exception.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
value : object or None
The text value of this widget when it first renders. This will be
cast to str internally. If ``None``, will initialize empty and
return ``None`` until the user provides input. Defaults to empty string.
max_chars : int or None
Max number of characters allowed in text input.
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. No two widgets may have the same key.
type : "default" or "password"
The type of the text input. This can be either "default" (for
a regular text input), or "password" (for a text input that
masks the user's typed value). Defaults to "default".
help : str or None
A tooltip that gets displayed next to the widget label. Streamlit
only displays the tooltip when ``label_visibility="visible"``. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
autocomplete : str
An optional value that will be passed to the <input> element's
autocomplete property. If unspecified, this value will be set to
"new-password" for "password" inputs, and the empty string for
"default" inputs. For more details, see https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete
on_change : callable
An optional callback invoked when this text input's value changes.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
placeholder : str or None
An optional string displayed when the text input is empty. If None,
no text is displayed.
disabled : bool
An optional boolean that disables the text input if set to
``True``. The default is ``False``.
label_visibility : "visible", "hidden", or "collapsed"
The visibility of the label. The default is ``"visible"``. If this
is ``"hidden"``, Streamlit displays an empty spacer instead of the
label, which can help keep the widget aligned with other widgets.
icon : str, None
An optional emoji or icon to display within the input field to the
left of the value. If ``icon`` is ``None`` (default), no icon is
displayed. If ``icon`` is a string, the following options are
valid:
- A single-character emoji. For example, you can set ``icon="🚨"``
or ``icon="🔥"``. Emoji short codes are not supported.
- An icon from the Material Symbols library (rounded style) in the
format ``":material/icon_name:"`` where "icon_name" is the name
of the icon in snake case.
For example, ``icon=":material/thumb_up:"`` will display the
Thumb Up icon. Find additional icons in the `Material Symbols \
<https://fonts.google.com/icons?icon.set=Material+Symbols&icon.style=Rounded>`_
font library.
- ``"spinner"``: Displays a spinner as an icon.
width : "stretch" or int
The width of the text input widget. This can be one of the
following:
- ``"stretch"`` (default): The width of the widget matches the
width of the parent container.
- An integer specifying the width in pixels: The widget has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the widget matches the width
of the parent container.
Returns
-------
str or None
The current value of the text input widget or ``None`` if no value has been
provided by the user.
Example
-------
>>> import streamlit as st
>>>
>>> title = st.text_input("Movie title", "Life of Brian")
>>> st.write("The current movie title is", title)
.. output::
https://doc-text-input.streamlit.app/
height: 260px
"""
ctx = get_script_run_ctx()
return self._text_input(
label=label,
value=value,
max_chars=max_chars,
key=key,
type=type,
help=help,
autocomplete=autocomplete,
on_change=on_change,
args=args,
kwargs=kwargs,
placeholder=placeholder,
disabled=disabled,
label_visibility=label_visibility,
icon=icon,
width=width,
ctx=ctx,
)
def _text_input(
self,
label: str,
value: SupportsStr | None = "",
max_chars: int | None = None,
key: Key | None = None,
type: str = "default",
help: str | None = None,
autocomplete: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
icon: str | None = None,
width: WidthWithoutContent = "stretch",
ctx: ScriptRunContext | None = None,
) -> str | None:
key = to_key(key)
check_widget_policies(
self.dg,
key,
on_change,
default_value=None if value == "" else value,
)
maybe_raise_label_warnings(label, label_visibility)
# Make sure value is always string or None:
value = str(value) if value is not None else None
element_id = compute_and_register_element_id(
"text_input",
user_key=key,
# Explicitly whitelist max_chars to make sure the ID changes when it changes
# since the widget value might become invalid based on a different max_chars
key_as_main_identity={"max_chars"},
dg=self.dg,
label=label,
value=value,
max_chars=max_chars,
type=type,
help=help,
autocomplete=autocomplete,
placeholder=str(placeholder),
icon=icon,
width=width,
)
session_state = get_session_state().filtered_state
if key is not None and key in session_state and session_state[key] is None:
value = None
text_input_proto = TextInputProto()
text_input_proto.id = element_id
text_input_proto.label = label
if value is not None:
text_input_proto.default = value
text_input_proto.form_id = current_form_id(self.dg)
text_input_proto.disabled = disabled
text_input_proto.label_visibility.value = get_label_visibility_proto_value(
label_visibility
)
if help is not None:
text_input_proto.help = dedent(help)
if max_chars is not None:
text_input_proto.max_chars = max_chars
if placeholder is not None:
text_input_proto.placeholder = str(placeholder)
if icon is not None:
text_input_proto.icon = validate_icon_or_emoji(icon)
if type == "default":
text_input_proto.type = TextInputProto.DEFAULT
elif type == "password":
text_input_proto.type = TextInputProto.PASSWORD
else:
raise StreamlitAPIException(
f"'{type}' is not a valid text_input type. Valid types are 'default' and 'password'."
)
# Marshall the autocomplete param. If unspecified, this will be
# set to "new-password" for password inputs.
if autocomplete is None:
autocomplete = "new-password" if type == "password" else ""
text_input_proto.autocomplete = autocomplete
serde = TextInputSerde(value)
widget_state = register_widget(
text_input_proto.id,
on_change_handler=on_change,
args=args,
kwargs=kwargs,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="string_value",
)
if widget_state.value_changed:
if widget_state.value is not None:
text_input_proto.value = widget_state.value
text_input_proto.set_value = True
validate_width(width)
layout_config = LayoutConfig(width=width)
self.dg._enqueue("text_input", text_input_proto, layout_config=layout_config)
return widget_state.value
@overload
def text_area(
self,
label: str,
value: str = "",
height: Height | None = None,
max_chars: int | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> str:
pass
@overload
def text_area(
self,
label: str,
value: SupportsStr | None = None,
height: Height | None = None,
max_chars: int | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> str | None:
pass
@gather_metrics("text_area")
def text_area(
self,
label: str,
value: str | SupportsStr | None = "",
height: Height | None = None,
max_chars: int | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> str | None:
r"""Display a multi-line text input widget.
Parameters
----------
label : str
A short label explaining to the user what this input is for.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
For accessibility reasons, you should never set an empty label, but
you can hide it with ``label_visibility`` if needed. In the future,
we may disallow empty labels by raising an exception.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
value : object or None
The text value of this widget when it first renders. This will be
cast to str internally. If ``None``, will initialize empty and
return ``None`` until the user provides input. Defaults to empty string.
height : "content", "stretch", int, or None
The height of the text area widget. This can be one of the
following:
- ``None`` (default): The height of the widget fits three lines.
- ``"content"``: The height of the widget matches the
height of its content.
- ``"stretch"``: The height of the widget matches the height of
its content or the height of the parent container, whichever is
larger. If the widget is not in a parent container, the height
of the widget matches the height of its content.
- An integer specifying the height in pixels: The widget has a
fixed height. If the content is larger than the specified
height, scrolling is enabled.
The widget's height can't be smaller than the height of two lines.
When ``label_visibility="collapsed"``, the minimum height is 68
pixels. Otherwise, the minimum height is 98 pixels.
max_chars : int or None
Maximum number of characters allowed in text area.
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. No two widgets may have the same key.
help : str or None
A tooltip that gets displayed next to the widget label. Streamlit
only displays the tooltip when ``label_visibility="visible"``. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
on_change : callable
An optional callback invoked when this text_area's value changes.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
placeholder : str or None
An optional string displayed when the text area is empty. If None,
no text is displayed.
disabled : bool
An optional boolean that disables the text area if set to ``True``.
The default is ``False``.
label_visibility : "visible", "hidden", or "collapsed"
The visibility of the label. The default is ``"visible"``. If this
is ``"hidden"``, Streamlit displays an empty spacer instead of the
label, which can help keep the widget aligned with other widgets.
If this is ``"collapsed"``, Streamlit displays no label or spacer.
width : "stretch" or int
The width of the text area widget. This can be one of the
following:
- ``"stretch"`` (default): The width of the widget matches the
width of the parent container.
- An integer specifying the width in pixels: The widget has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the widget matches the width
of the parent container.
Returns
-------
str or None
The current value of the text area widget or ``None`` if no value has been
provided by the user.
Example
-------
>>> import streamlit as st
>>>
>>> txt = st.text_area(
... "Text to analyze",
... "It was the best of times, it was the worst of times, it was the age of "
... "wisdom, it was the age of foolishness, it was the epoch of belief, it "
... "was the epoch of incredulity, it was the season of Light, it was the "
... "season of Darkness, it was the spring of hope, it was the winter of "
... "despair, (...)",
... )
>>>
>>> st.write(f"You wrote {len(txt)} characters.")
.. output::
https://doc-text-area.streamlit.app/
height: 300px
"""
ctx = get_script_run_ctx()
return self._text_area(
label=label,
value=value,
height=height,
max_chars=max_chars,
key=key,
help=help,
on_change=on_change,
args=args,
kwargs=kwargs,
placeholder=placeholder,
disabled=disabled,
label_visibility=label_visibility,
width=width,
ctx=ctx,
)
def _text_area(
self,
label: str,
value: SupportsStr | None = "",
height: Height | None = None,
max_chars: int | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
ctx: ScriptRunContext | None = None,
) -> str | None:
key = to_key(key)
check_widget_policies(
self.dg,
key,
on_change,
default_value=None if value == "" else value,
)
maybe_raise_label_warnings(label, label_visibility)
value = str(value) if value is not None else None
element_id = compute_and_register_element_id(
"text_area",
user_key=key,
# Explicitly whitelist max_chars to make sure the ID changes when it changes
# since the widget value might become invalid based on a different max_chars
key_as_main_identity={"max_chars"},
dg=self.dg,
label=label,
value=value,
height=height,
max_chars=max_chars,
help=help,
placeholder=str(placeholder),
width=width,
)
session_state = get_session_state().filtered_state
if key is not None and key in session_state and session_state[key] is None:
value = None
text_area_proto = TextAreaProto()
text_area_proto.id = element_id
text_area_proto.label = label
if value is not None:
text_area_proto.default = value
text_area_proto.form_id = current_form_id(self.dg)
text_area_proto.disabled = disabled
text_area_proto.label_visibility.value = get_label_visibility_proto_value(
label_visibility
)
if help is not None:
text_area_proto.help = dedent(help)
if max_chars is not None:
text_area_proto.max_chars = max_chars
if placeholder is not None:
text_area_proto.placeholder = str(placeholder)
serde = TextAreaSerde(value)
widget_state = register_widget(
text_area_proto.id,
on_change_handler=on_change,
args=args,
kwargs=kwargs,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="string_value",
)
if widget_state.value_changed:
if widget_state.value is not None:
text_area_proto.value = widget_state.value
text_area_proto.set_value = True
validate_width(width)
if height is not None:
validate_height(height, allow_content=True)
else:
# We want to maintain the same approximately three lines of text height
# for the text input when the label is collapsed.
# These numbers are for the entire element including the label and
# padding.
height = 122 if label_visibility != "collapsed" else 94
layout_config = LayoutConfig(width=width, height=height)
self.dg._enqueue("text_area", text_area_proto, layout_config=layout_config)
return widget_state.value
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/widgets/button.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import io
import os
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
from textwrap import dedent
from typing import (
TYPE_CHECKING,
BinaryIO,
Final,
Literal,
TextIO,
TypeAlias,
cast,
)
from streamlit import runtime
from streamlit.elements.lib.form_utils import current_form_id, is_in_form
from streamlit.elements.lib.layout_utils import LayoutConfig, Width, validate_width
from streamlit.elements.lib.policies import check_widget_policies
from streamlit.elements.lib.shortcut_utils import normalize_shortcut
from streamlit.elements.lib.utils import (
Key,
compute_and_register_element_id,
save_for_app_testing,
to_key,
)
from streamlit.errors import (
StreamlitAPIException,
StreamlitMissingPageLabelError,
StreamlitPageNotFoundError,
)
from streamlit.file_util import get_main_script_directory, normalize_path_join
from streamlit.navigation.page import StreamlitPage
from streamlit.proto.Button_pb2 import Button as ButtonProto
from streamlit.proto.DownloadButton_pb2 import DownloadButton as DownloadButtonProto
from streamlit.proto.LinkButton_pb2 import LinkButton as LinkButtonProto
from streamlit.proto.PageLink_pb2 import PageLink as PageLinkProto
from streamlit.runtime.download_data_util import convert_data_to_bytes_and_infer_mime
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.pages_manager import PagesManager
from streamlit.runtime.scriptrunner import ScriptRunContext, get_script_run_ctx
from streamlit.runtime.state import (
WidgetArgs,
WidgetCallback,
WidgetKwargs,
register_widget,
)
from streamlit.runtime.state.query_params import process_query_params
from streamlit.string_util import validate_icon_or_emoji
from streamlit.url_util import is_url
from streamlit.util import in_sidebar
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
from streamlit.runtime.state.query_params import QueryParamsInput
FORM_DOCS_INFO: Final = """
For more information, refer to the
[documentation for forms](https://docs.streamlit.io/develop/api-reference/execution-flow/st.form).
"""
DownloadButtonDataType: TypeAlias = (
str
| bytes
| TextIO
| BinaryIO
| io.RawIOBase
| Callable[[], str | bytes | TextIO | BinaryIO | io.RawIOBase]
)
@dataclass
class ButtonSerde:
def serialize(self, v: bool) -> bool:
return bool(v)
def deserialize(self, ui_value: bool | None) -> bool:
return ui_value or False
class ButtonMixin:
@gather_metrics("button")
def button(
self,
label: str,
key: Key | None = None,
help: str | None = None,
on_click: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
type: Literal["primary", "secondary", "tertiary"] = "secondary",
icon: str | None = None,
disabled: bool = False,
use_container_width: bool | None = None,
width: Width = "content",
shortcut: str | None = None,
) -> bool:
r"""Display a button widget.
Parameters
----------
label : str
A short label explaining to the user what this button is for.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. No two widgets may have the same key.
help : str or None
A tooltip that gets displayed when the button is hovered over. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
on_click : callable
An optional callback invoked when this button is clicked.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
type : "primary", "secondary", or "tertiary"
An optional string that specifies the button type. This can be one
of the following:
- ``"primary"``: The button's background is the app's primary color
for additional emphasis.
- ``"secondary"`` (default): The button's background coordinates
with the app's background color for normal emphasis.
- ``"tertiary"``: The button is plain text without a border or
background for subtlety.
icon : str or None
An optional emoji or icon to display next to the button label. If ``icon``
is ``None`` (default), no icon is displayed. If ``icon`` is a
string, the following options are valid:
- A single-character emoji. For example, you can set ``icon="🚨"``
or ``icon="🔥"``. Emoji short codes are not supported.
- An icon from the Material Symbols library (rounded style) in the
format ``":material/icon_name:"`` where "icon_name" is the name
of the icon in snake case.
For example, ``icon=":material/thumb_up:"`` will display the
Thumb Up icon. Find additional icons in the `Material Symbols \
<https://fonts.google.com/icons?icon.set=Material+Symbols&icon.style=Rounded>`_
font library.
- ``"spinner"``: Displays a spinner as an icon.
disabled : bool
An optional boolean that disables the button if set to ``True``.
The default is ``False``.
use_container_width : bool
Whether to expand the button's width to fill its parent container.
If ``use_container_width`` is ``False`` (default), Streamlit sizes
the button to fit its contents. If ``use_container_width`` is
``True``, the width of the button matches its parent container.
In both cases, if the contents of the button are wider than the
parent container, the contents will line wrap.
.. deprecated::
``use_container_width`` is deprecated and will be removed in a
future release. For ``use_container_width=True``, use
``width="stretch"``. For ``use_container_width=False``, use
``width="content"``.
width : "content", "stretch", or int
The width of the button. This can be one of the following:
- ``"content"`` (default): The width of the button matches the
width of its content, but doesn't exceed the width of the parent
container.
- ``"stretch"``: The width of the button matches the width of the
parent container.
- An integer specifying the width in pixels: The button has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the button matches the width
of the parent container.
shortcut : str or None
An optional keyboard shortcut that triggers the button. This can be
one of the following strings:
- A single alphanumeric key like ``"K"`` or ``"4"``.
- A function key like ``"F11"``.
- A special key like ``"Enter"``, ``"Esc"``, or ``"Tab"``.
- Any of the above combined with modifiers. For example, you can use
``"Ctrl+K"`` or ``"Cmd+Shift+O"``.
.. important::
The keys ``"C"`` and ``"R"`` are reserved and can't be used,
even with modifiers. Punctuation keys like ``"."`` and ``","``
aren't currently supported.
The following special keys are supported: Backspace, Delete, Down,
End, Enter, Esc, Home, Left, PageDown, PageUp, Right, Space, Tab,
and Up.
The following modifiers are supported: Alt, Ctrl, Cmd, Meta, Mod,
Option, Shift.
- Ctrl, Cmd, Meta, and Mod are interchangeable and will display to
the user to match their platform.
- Option and Alt are interchangeable and will display to the user
to match their platform.
Returns
-------
bool
True if the button was clicked on the last run of the app,
False otherwise.
Examples
--------
**Example 1: Customize your button type**
>>> import streamlit as st
>>>
>>> st.button("Reset", type="primary")
>>> if st.button("Say hello"):
... st.write("Why hello there")
... else:
... st.write("Goodbye")
>>>
>>> if st.button("Aloha", type="tertiary"):
... st.write("Ciao")
.. output::
https://doc-buton.streamlit.app/
height: 300px
**Example 2: Add icons to your button**
Although you can add icons to your buttons through Markdown, the
``icon`` parameter is a convenient and consistent alternative.
>>> import streamlit as st
>>>
>>> left, middle, right = st.columns(3)
>>> if left.button("Plain button", width="stretch"):
... left.markdown("You clicked the plain button.")
>>> if middle.button("Emoji button", icon="😃", width="stretch"):
... middle.markdown("You clicked the emoji button.")
>>> if right.button("Material button", icon=":material/mood:", width="stretch"):
... right.markdown("You clicked the Material button.")
.. output::
https://doc-button-icons.streamlit.app/
height: 220px
**Example 3: Use keyboard shortcuts**
The following example shows how to use keyboard shortcuts to trigger a
button. If you use any of the platform-dependent modifiers (Ctrl, Cmd,
or Mod), they are interpreted interchangeably and always displayed to
the user to match their platform.
>>> import streamlit as st
>>>
>>> with st.container(horizontal=True, horizontal_alignment="distribute"):
>>> "`A`" if st.button("A", shortcut="A") else "` `"
>>> "`S`" if st.button("S", shortcut="Ctrl+S") else "` `"
>>> "`D`" if st.button("D", shortcut="Cmd+Shift+D") else "` `"
>>> "`F`" if st.button("F", shortcut="Mod+Alt+Shift+F") else "` `"
.. output::
https://doc-button-shortcuts.streamlit.app/
height: 220px
"""
key = to_key(key)
ctx = get_script_run_ctx()
if use_container_width is not None:
width = "stretch" if use_container_width else "content"
# Checks whether the entered button type is one of the allowed options
if type not in ["primary", "secondary", "tertiary"]:
raise StreamlitAPIException(
'The type argument to st.button must be "primary", "secondary", or "tertiary". '
f'\nThe argument passed was "{type}".'
)
return self.dg._button(
label,
key,
help,
is_form_submitter=False,
on_click=on_click,
args=args,
kwargs=kwargs,
disabled=disabled,
type=type,
icon=icon,
ctx=ctx,
width=width,
shortcut=shortcut,
)
@gather_metrics("download_button")
def download_button(
self,
label: str,
data: DownloadButtonDataType,
file_name: str | None = None,
mime: str | None = None,
key: Key | None = None,
help: str | None = None,
on_click: WidgetCallback | Literal["rerun", "ignore"] | None = "rerun",
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
type: Literal["primary", "secondary", "tertiary"] = "secondary",
icon: str | None = None,
disabled: bool = False,
use_container_width: bool | None = None,
width: Width = "content",
shortcut: str | None = None,
) -> bool:
r"""Display a download button widget.
This is useful when you would like to provide a way for your users
to download a file directly from your app.
If you pass the data directly to the ``data`` parameter, then the data
is stored in-memory while the user is connected. It's a good idea to
keep file sizes under a couple hundred megabytes to conserve memory or
use deferred data generation by passing a callable to the ``data``
parameter.
If you want to prevent your app from rerunning when a user clicks the
download button, wrap the download button in a `fragment
<https://docs.streamlit.io/develop/concepts/architecture/fragments>`_.
Parameters
----------
label : str
A short label explaining to the user what this button is for.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
data : str, bytes, file-like, or callable
The contents of the file to be downloaded or a callable that
returns the contents of the file.
File contents can be a string, bytes, or file-like object.
File-like objects include ``io.BytesIO``, ``io.StringIO``, or any
class that implements the abstract base class ``io.RawIOBase``.
If a callable is passed, it is executed when the user clicks
the download button and runs on a separate thread from the
resulting script rerun. This deferred generation is helpful for
large files to avoid blocking the page script. The callable can't
accept any arguments. If any Streamlit commands are executed inside
the callable, they will be ignored.
To prevent unnecessary recomputation, use caching when converting
your data for download. For more information, see the Example 1
below.
file_name: str
An optional string to use as the name of the file to be downloaded,
such as ``"my_file.csv"``. If not specified, the name will be
automatically generated.
mime : str or None
The MIME type of the data. If this is ``None`` (default), Streamlit
sets the MIME type depending on the value of ``data`` as follows:
- If ``data`` is a string or textual file (i.e. ``str`` or
``io.TextIOWrapper`` object), Streamlit uses the "text/plain"
MIME type.
- If ``data`` is a binary file or bytes (i.e. ``bytes``,
``io.BytesIO``, ``io.BufferedReader``, or ``io.RawIOBase``
object), Streamlit uses the "application/octet-stream" MIME type.
For more information about MIME types, see
https://www.iana.org/assignments/media-types/media-types.xhtml.
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. No two widgets may have the same key.
help : str or None
A tooltip that gets displayed when the button is hovered over. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
on_click : callable, "rerun", "ignore", or None
How the button should respond to user interaction. This controls
whether or not the button triggers a rerun and if a callback
function is called. This can be one of the following values:
- ``"rerun"`` (default): The user downloads the file and the app
reruns. No callback function is called.
- ``"ignore"``: The user downloads the file and the app doesn't
rerun. No callback function is called.
- A ``callable``: The user downloads the file and app reruns. The
callable is called before the rest of the app.
- ``None``: This is same as ``on_click="rerun"``. This value exists
for backwards compatibility and shouldn't be used.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
type : "primary", "secondary", or "tertiary"
An optional string that specifies the button type. This can be one
of the following:
- ``"primary"``: The button's background is the app's primary color
for additional emphasis.
- ``"secondary"`` (default): The button's background coordinates
with the app's background color for normal emphasis.
- ``"tertiary"``: The button is plain text without a border or
background for subtlety.
icon : str or None
An optional emoji or icon to display next to the button label. If ``icon``
is ``None`` (default), no icon is displayed. If ``icon`` is a
string, the following options are valid:
- A single-character emoji. For example, you can set ``icon="🚨"``
or ``icon="🔥"``. Emoji short codes are not supported.
- An icon from the Material Symbols library (rounded style) in the
format ``":material/icon_name:"`` where "icon_name" is the name
of the icon in snake case.
For example, ``icon=":material/thumb_up:"`` will display the
Thumb Up icon. Find additional icons in the `Material Symbols \
<https://fonts.google.com/icons?icon.set=Material+Symbols&icon.style=Rounded>`_
font library.
- ``"spinner"``: Displays a spinner as an icon.
disabled : bool
An optional boolean that disables the download button if set to
``True``. The default is ``False``.
use_container_width : bool
Whether to expand the button's width to fill its parent container.
If ``use_container_width`` is ``False`` (default), Streamlit sizes
the button to fit its contents. If ``use_container_width`` is
``True``, the width of the button matches its parent container.
In both cases, if the contents of the button are wider than the
parent container, the contents will line wrap.
.. deprecated::
``use_container_width`` is deprecated and will be removed in a
future release. For ``use_container_width=True``, use
``width="stretch"``. For ``use_container_width=False``, use
``width="content"``.
width : "content", "stretch", or int
The width of the download button. This can be one of the following:
- ``"content"`` (default): The width of the button matches the
width of its content, but doesn't exceed the width of the parent
container.
- ``"stretch"``: The width of the button matches the width of the
parent container.
- An integer specifying the width in pixels: The button has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the button matches the width
of the parent container.
shortcut : str or None
An optional keyboard shortcut that triggers the button. This can be
one of the following strings:
- A single alphanumeric key like ``"K"`` or ``"4"``.
- A function key like ``"F11"``.
- A special key like ``"Enter"``, ``"Esc"``, or ``"Tab"``.
- Any of the above combined with modifiers. For example, you can use
``"Ctrl+K"`` or ``"Cmd+Shift+O"``.
.. important::
The keys ``"C"`` and ``"R"`` are reserved and can't be used,
even with modifiers. Punctuation keys like ``"."`` and ``","``
aren't currently supported.
For a list of supported keys and modifiers, see the documentation
for |st.button|_.
.. |st.button| replace:: ``st.button``
.. _st.button: https://docs.streamlit.io/develop/api-reference/widgets/st.button
Returns
-------
bool
True if the button was clicked on the last run of the app,
False otherwise.
Examples
--------
**Example 1: Download a dataframe as a CSV file**
When working with a large dataframe, it's recommended to fetch your
data with a cached function. When working with a download button, it's
similarly recommended to convert your data into a downloadable format
with a cached function. Caching ensures that the app reruns
efficiently.
>>> import streamlit as st
>>> import pandas as pd
>>> import numpy as np
>>>
>>> @st.cache_data
>>> def get_data():
>>> df = pd.DataFrame(
... np.random.randn(50, 20), columns=("col %d" % i for i in range(20))
... )
>>> return df
>>>
>>> @st.cache_data
>>> def convert_for_download(df):
>>> return df.to_csv().encode("utf-8")
>>>
>>> df = get_data()
>>> csv = convert_for_download(df)
>>>
>>> st.download_button(
... label="Download CSV",
... data=csv,
... file_name="data.csv",
... mime="text/csv",
... icon=":material/download:",
... )
.. output::
https://doc-download-button-csv.streamlit.app/
height: 200px
**Example 2: Download a string as a text file**
If you pass a string to the ``data`` argument, Streamlit will
automatically use the "text/plain" MIME type.
When you have a widget (like a text area) affecting the value of your
download, it's recommended to use another button to prepare the
download. In this case, use ``on_click="ignore"`` in your download
button to prevent the download button from rerunning your app. This
turns the download button into a frontend-only element that can be
nested in another button.
Without a preparation button, a user can type something into the text
area and immediately click the download button. Because a download is
initiated concurrently with the app rerun, this can create a race-like
condition where the user doesn't see the updated data in their
download.
.. important::
Even when you prevent your download button from triggering a rerun,
another widget with a pending change can still trigger a rerun. For
example, if a text area has a pending change when a user clicks a
download button, the text area will trigger a rerun.
>>> import streamlit as st
>>>
>>> message = st.text_area("Message", value="Lorem ipsum.\nStreamlit is cool.")
>>>
>>> if st.button("Prepare download"):
>>> st.download_button(
... label="Download text",
... data=message,
... file_name="message.txt",
... on_click="ignore",
... type="primary",
... icon=":material/download:",
... )
.. output::
https://doc-download-button-text.streamlit.app/
height: 250px
**Example 3: Download a file**
Use a context manager to open and read a local file on your Streamlit
server. Pass the ``io.BufferedReader`` object directly to ``data``.
Remember to specify the MIME type if you don't want the default
type of ``"application/octet-stream"`` for generic binary data. In the
example below, the MIME type is set to ``"image/png"`` for a PNG file.
>>> import streamlit as st
>>>
>>> with open("flower.png", "rb") as file:
... st.download_button(
... label="Download image",
... data=file,
... file_name="flower.png",
... mime="image/png",
... )
.. output::
https://doc-download-button-file.streamlit.app/
height: 200px
**Example 4: Generate the data on-click with a callable**
Pass a callable to ``data`` to generate the bytes lazily when the user
clicks the button. Streamlit commands inside this callable are ignored.
The callable can't accept any arguments and must return a file-like
object.
>>> import streamlit as st
>>> import time
>>>
>>> def make_report():
>>> time.sleep(1)
>>> return "col1,col2\n1,2\n3,4".encode("utf-8")
>>>
>>> st.download_button(
... label="Download report",
... data=make_report,
... file_name="report.csv",
... mime="text/csv",
... )
.. output::
https://doc-download-button-deferred.streamlit.app/
height: 200px
"""
ctx = get_script_run_ctx()
if use_container_width is not None:
width = "stretch" if use_container_width else "content"
if type not in ["primary", "secondary", "tertiary"]:
raise StreamlitAPIException(
'The type argument to st.download_button must be "primary", "secondary", or "tertiary". \n'
f'The argument passed was "{type}".'
)
return self._download_button(
label=label,
data=data,
file_name=file_name,
mime=mime,
key=key,
help=help,
on_click=on_click,
args=args,
kwargs=kwargs,
type=type,
icon=icon,
disabled=disabled,
ctx=ctx,
width=width,
shortcut=shortcut,
)
@gather_metrics("link_button")
def link_button(
self,
label: str,
url: str,
*,
help: str | None = None,
type: Literal["primary", "secondary", "tertiary"] = "secondary",
icon: str | None = None,
disabled: bool = False,
use_container_width: bool | None = None,
width: Width = "content",
shortcut: str | None = None,
) -> DeltaGenerator:
r"""Display a link button element.
When clicked, a new tab will be opened to the specified URL. This will
create a new session for the user if directed within the app.
Parameters
----------
label : str
A short label explaining to the user what this button is for.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
url : str
The url to be opened on user click
help : str or None
A tooltip that gets displayed when the button is hovered over. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
type : "primary", "secondary", or "tertiary"
An optional string that specifies the button type. This can be one
of the following:
- ``"primary"``: The button's background is the app's primary color
for additional emphasis.
- ``"secondary"`` (default): The button's background coordinates
with the app's background color for normal emphasis.
- ``"tertiary"``: The button is plain text without a border or
background for subtlety.
icon : str or None
An optional emoji or icon to display next to the button label. If ``icon``
is ``None`` (default), no icon is displayed. If ``icon`` is a
string, the following options are valid:
- A single-character emoji. For example, you can set ``icon="🚨"``
or ``icon="🔥"``. Emoji short codes are not supported.
- An icon from the Material Symbols library (rounded style) in the
format ``":material/icon_name:"`` where "icon_name" is the name
of the icon in snake case.
For example, ``icon=":material/thumb_up:"`` will display the
Thumb Up icon. Find additional icons in the `Material Symbols \
<https://fonts.google.com/icons?icon.set=Material+Symbols&icon.style=Rounded>`_
font library.
- ``"spinner"``: Displays a spinner as an icon.
disabled : bool
An optional boolean that disables the link button if set to
``True``. The default is ``False``.
use_container_width : bool
Whether to expand the button's width to fill its parent container.
If ``use_container_width`` is ``False`` (default), Streamlit sizes
the button to fit its contents. If ``use_container_width`` is
``True``, the width of the button matches its parent container.
In both cases, if the contents of the button are wider than the
parent container, the contents will line wrap.
.. deprecated::
``use_container_width`` is deprecated and will be removed in a
future release. For ``use_container_width=True``, use
``width="stretch"``. For ``use_container_width=False``, use
``width="content"``.
width : "content", "stretch", or int
The width of the link button. This can be one of the following:
- ``"content"`` (default): The width of the button matches the
width of its content, but doesn't exceed the width of the parent
container.
- ``"stretch"``: The width of the button matches the width of the
parent container.
- An integer specifying the width in pixels: The button has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the button matches the width
of the parent container.
shortcut : str or None
An optional keyboard shortcut that triggers the button. This can be
one of the following strings:
- A single alphanumeric key like ``"K"`` or ``"4"``.
- A function key like ``"F11"``.
- A special key like ``"Enter"``, ``"Esc"``, or ``"Tab"``.
- Any of the above combined with modifiers. For example, you can use
``"Ctrl+K"`` or ``"Cmd+Shift+O"``.
.. important::
The keys ``"C"`` and ``"R"`` are reserved and can't be used,
even with modifiers. Punctuation keys like ``"."`` and ``","``
aren't currently supported.
For a list of supported keys and modifiers, see the documentation
for |st.button|_.
.. |st.button| replace:: ``st.button``
.. _st.button: https://docs.streamlit.io/develop/api-reference/widgets/st.button
Example
-------
>>> import streamlit as st
>>>
>>> st.link_button("Go to gallery", "https://streamlit.io/gallery")
.. output::
https://doc-link-button.streamlit.app/
height: 200px
"""
# Checks whether the entered button type is one of the allowed options - either "primary" or "secondary"
if type not in ["primary", "secondary", "tertiary"]:
raise StreamlitAPIException(
'The type argument to st.link_button must be "primary", "secondary", or "tertiary". '
f'\nThe argument passed was "{type}".'
)
if use_container_width is not None:
width = "stretch" if use_container_width else "content"
return self._link_button(
label=label,
url=url,
help=help,
disabled=disabled,
type=type,
icon=icon,
width=width,
shortcut=shortcut,
)
@gather_metrics("page_link")
def page_link(
self,
page: str | Path | StreamlitPage,
*,
label: str | None = None,
icon: str | None = None,
help: str | None = None,
disabled: bool = False,
use_container_width: bool | None = None,
width: Width = "content",
query_params: QueryParamsInput | None = None,
) -> DeltaGenerator:
r"""Display a link to another page in a multipage app or to an external page.
If another page in a multipage app is specified, clicking ``st.page_link``
stops the current page execution and runs the specified page as if the
user clicked on it in the sidebar navigation.
If an external page is specified, clicking ``st.page_link`` opens a new
tab to the specified page. The current script run will continue if not
complete.
Parameters
----------
page : str, Path, or StreamlitPage
The file path (relative to the main script) or a ``StreamlitPage``
indicating the page to switch to. Alternatively, this can be the
URL to an external page (must start with "http://" or "https://").
label : str
The label for the page link. Labels are required for external pages.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
icon : str or None
An optional emoji or icon to display next to the button label. If
``icon`` is ``None`` (default), the icon is inferred from the
``StreamlitPage`` object or no icon is displayed. If ``icon`` is a
string, the following options are valid:
- A single-character emoji. For example, you can set ``icon="🚨"``
or ``icon="🔥"``. Emoji short codes are not supported.
- An icon from the Material Symbols library (rounded style) in the
format ``":material/icon_name:"`` where "icon_name" is the name
of the icon in snake case.
For example, ``icon=":material/thumb_up:"`` will display the
Thumb Up icon. Find additional icons in the `Material Symbols \
<https://fonts.google.com/icons?icon.set=Material+Symbols&icon.style=Rounded>`_
font library.
- ``"spinner"``: Displays a spinner as an icon.
help : str or None
A tooltip that gets displayed when the link is hovered over. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
disabled : bool
An optional boolean that disables the page link if set to ``True``.
The default is ``False``.
use_container_width : bool
Whether to expand the link's width to fill its parent container.
The default is ``True`` for page links in the sidebar and ``False``
for those in the main app.
.. deprecated::
``use_container_width`` is deprecated and will be removed in a
future release. For ``use_container_width=True``, use
``width="stretch"``. For ``use_container_width=False``, use
``width="content"``.
width : "content", "stretch", or int
The width of the page-link button. This can be one of the following:
- ``"content"`` (default): The width of the button matches the
width of its content, but doesn't exceed the width of the parent
container.
- ``"stretch"``: The width of the button matches the width of the
parent container.
- An integer specifying the width in pixels: The button has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the button matches the width
of the parent container.
query_params : dict, list of tuples, or None
Query parameters to apply when navigating to the target page.
This can be a dictionary or an iterable of key-value tuples. Values can
be strings or iterables of strings (for repeated keys). When this is
``None`` (default), all non-embed query parameters are cleared during
navigation.
Example
-------
**Example 1: Basic usage**
The following example shows how to create page links in a multipage app
that uses the ``pages/`` directory:
.. code-block:: text
your-repository/
├── pages/
│ ├── page_1.py
│ └── page_2.py
└── your_app.py
>>> import streamlit as st
>>>
>>> st.page_link("your_app.py", label="Home", icon="🏠")
>>> st.page_link("pages/page_1.py", label="Page 1", icon="1️⃣")
>>> st.page_link("pages/page_2.py", label="Page 2", icon="2️⃣", disabled=True)
>>> st.page_link("http://www.google.com", label="Google", icon="🌎")
The default navigation is shown here for comparison, but you can hide
the default navigation using the |client.showSidebarNavigation|_
configuration option. This allows you to create custom, dynamic
navigation menus for your apps!
.. |client.showSidebarNavigation| replace:: ``client.showSidebarNavigation``
.. _client.showSidebarNavigation: https://docs.streamlit.io/develop/api-reference/configuration/config.toml#client
.. output::
https://doc-page-link.streamlit.app/
height: 350px
**Example 2: Passing query parameters**
The following example shows how to pass query parameters when creating a
page link in a multipage app:
.. code-block:: text
your-repository/
├── page_2.py
└── your_app.py
>>> import streamlit as st
>>>
>>> def page_1():
>>> st.title("Page 1")
>>> st.page_link("page_2.py", query_params={"utm_source": "page_1"})
>>>
>>> pg = st.navigation([page_1, "page_2.py"])
>>> pg.run()
.. output::
https://doc-page-link-query-params.streamlit.app/
height: 350px
"""
if use_container_width is not None:
width = "stretch" if use_container_width else "content"
if in_sidebar(self.dg):
# Sidebar page links should always be stretch width.
width = "stretch"
return self._page_link(
page=page,
label=label,
icon=icon,
help=help,
disabled=disabled,
width=width,
query_params=query_params,
)
def _download_button(
self,
label: str,
data: DownloadButtonDataType,
file_name: str | None = None,
mime: str | None = None,
key: Key | None = None,
help: str | None = None,
on_click: WidgetCallback | Literal["rerun", "ignore"] | None = "rerun",
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
type: Literal["primary", "secondary", "tertiary"] = "secondary",
icon: str | None = None,
disabled: bool = False,
ctx: ScriptRunContext | None = None,
width: Width = "content",
shortcut: str | None = None,
) -> bool:
key = to_key(key)
on_click_callback: WidgetCallback | None = (
None
if on_click is None or on_click in {"ignore", "rerun"}
else cast("WidgetCallback", on_click)
)
normalized_shortcut: str | None = None
if shortcut is not None:
normalized_shortcut = normalize_shortcut(shortcut)
check_widget_policies(
self.dg,
key,
on_change=on_click_callback,
default_value=None,
writes_allowed=False,
)
element_id = compute_and_register_element_id(
"download_button",
user_key=key,
key_as_main_identity=True,
dg=self.dg,
label=label,
icon=icon,
file_name=file_name,
mime=mime,
help=help,
type=type,
width=width,
shortcut=normalized_shortcut,
)
if is_in_form(self.dg):
raise StreamlitAPIException(
f"`st.download_button()` can't be used in an `st.form()`.{FORM_DOCS_INFO}"
)
download_button_proto = DownloadButtonProto()
download_button_proto.id = element_id
download_button_proto.label = label
download_button_proto.default = False
download_button_proto.type = type
marshall_file(
self.dg._get_delta_path_str(), data, download_button_proto, mime, file_name
)
download_button_proto.disabled = disabled
if help is not None:
download_button_proto.help = dedent(help)
if icon is not None:
download_button_proto.icon = validate_icon_or_emoji(icon)
if on_click == "ignore":
download_button_proto.ignore_rerun = True
else:
download_button_proto.ignore_rerun = False
if normalized_shortcut is not None:
download_button_proto.shortcut = normalized_shortcut
serde = ButtonSerde()
button_state = register_widget(
download_button_proto.id,
on_change_handler=on_click_callback,
args=args,
kwargs=kwargs,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="trigger_value",
)
validate_width(width, allow_content=True)
layout_config = LayoutConfig(width=width)
self.dg._enqueue(
"download_button", download_button_proto, layout_config=layout_config
)
return button_state.value
def _link_button(
self,
label: str,
url: str,
help: str | None,
*, # keyword-only arguments:
type: Literal["primary", "secondary", "tertiary"] = "secondary",
icon: str | None = None,
disabled: bool = False,
width: Width = "content",
shortcut: str | None = None,
) -> DeltaGenerator:
link_button_proto = LinkButtonProto()
normalized_shortcut: str | None = None
if shortcut is not None:
normalized_shortcut = normalize_shortcut(shortcut)
if normalized_shortcut is not None:
# We only register the element ID if a shortcut is provide.
# The ID is required to correctly register and handle the shortcut
# on the client side.
link_button_proto.id = compute_and_register_element_id(
"link_button",
user_key=None,
key_as_main_identity=False,
dg=self.dg,
label=label,
icon=icon,
url=url,
help=help,
type=type,
width=width,
shortcut=normalized_shortcut,
)
link_button_proto.label = label
link_button_proto.url = url
link_button_proto.type = type
link_button_proto.disabled = disabled
if help is not None:
link_button_proto.help = dedent(help)
if icon is not None:
link_button_proto.icon = validate_icon_or_emoji(icon)
if normalized_shortcut is not None:
link_button_proto.shortcut = normalized_shortcut
validate_width(width, allow_content=True)
layout_config = LayoutConfig(width=width)
return self.dg._enqueue(
"link_button", link_button_proto, layout_config=layout_config
)
def _page_link(
self,
page: str | Path | StreamlitPage,
*, # keyword-only arguments:
label: str | None = None,
icon: str | None = None,
help: str | None = None,
disabled: bool = False,
width: Width = "content",
query_params: QueryParamsInput | None = None,
) -> DeltaGenerator:
page_link_proto = PageLinkProto()
if query_params:
page_link_proto.query_string = process_query_params(query_params)
validate_width(width, allow_content=True)
ctx = get_script_run_ctx()
if not ctx:
layout_config = LayoutConfig(width=width)
return self.dg._enqueue(
"page_link", page_link_proto, layout_config=layout_config
)
page_link_proto.disabled = disabled
if label is not None:
page_link_proto.label = label
if icon is not None:
page_link_proto.icon = validate_icon_or_emoji(icon)
if help is not None:
page_link_proto.help = dedent(help)
if isinstance(page, StreamlitPage):
page_link_proto.page_script_hash = page._script_hash
page_link_proto.page = page.url_path
if label is None:
page_link_proto.label = page.title
if icon is None:
page_link_proto.icon = page.icon
# Here the StreamlitPage's icon is already validated
# (using validate_icon_or_emoji) during its initialization
else:
# Convert Path to string if necessary
if isinstance(page, Path):
page = str(page)
# Handle external links:
if is_url(page):
if label is None or label == "":
raise StreamlitMissingPageLabelError()
page_link_proto.page = page
page_link_proto.external = True
layout_config = LayoutConfig(width=width)
return self.dg._enqueue(
"page_link", page_link_proto, layout_config=layout_config
)
ctx_main_script = ""
all_app_pages = {}
ctx_main_script = ctx.main_script_path
all_app_pages = ctx.pages_manager.get_pages()
main_script_directory = get_main_script_directory(ctx_main_script)
requested_page = os.path.realpath(
normalize_path_join(main_script_directory, page)
)
# Handle retrieving the page_script_hash & page
for page_data in all_app_pages.values():
full_path = page_data["script_path"]
page_name = page_data["page_name"]
url_pathname = page_data["url_pathname"]
if requested_page == full_path:
if label is None:
page_link_proto.label = page_name
page_link_proto.page_script_hash = page_data["page_script_hash"]
page_link_proto.page = url_pathname
break
if page_link_proto.page_script_hash == "":
raise StreamlitPageNotFoundError(
page=page,
main_script_directory=main_script_directory,
uses_pages_directory=bool(PagesManager.uses_pages_directory),
)
layout_config = LayoutConfig(width=width)
return self.dg._enqueue(
"page_link", page_link_proto, layout_config=layout_config
)
def _button(
self,
label: str,
key: str | None,
help: str | None,
is_form_submitter: bool,
on_click: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
type: Literal["primary", "secondary", "tertiary"] = "secondary",
icon: str | None = None,
disabled: bool = False,
ctx: ScriptRunContext | None = None,
width: Width = "content",
shortcut: str | None = None,
) -> bool:
key = to_key(key)
normalized_shortcut: str | None = None
if shortcut is not None:
normalized_shortcut = normalize_shortcut(shortcut)
check_widget_policies(
self.dg,
key,
on_click,
default_value=None,
writes_allowed=False,
enable_check_callback_rules=not is_form_submitter,
)
# Only the form submitter button needs a form ID at the moment.
form_id = current_form_id(self.dg) if is_form_submitter else ""
element_id = compute_and_register_element_id(
"form_submit_button" if is_form_submitter else "button",
user_key=key,
key_as_main_identity=True,
dg=self.dg,
label=label,
icon=icon,
help=help,
is_form_submitter=is_form_submitter,
type=type,
width=width,
shortcut=normalized_shortcut,
)
# It doesn't make sense to create a button inside a form (except
# for the "Form Submitter" button that's automatically created in
# every form). We throw an error to warn the user about this.
# We omit this check for scripts running outside streamlit, because
# they will have no script_run_ctx.
if runtime.exists():
if is_in_form(self.dg) and not is_form_submitter:
raise StreamlitAPIException(
f"`st.button()` can't be used in an `st.form()`.{FORM_DOCS_INFO}"
)
if not is_in_form(self.dg) and is_form_submitter:
raise StreamlitAPIException(
f"`st.form_submit_button()` must be used inside an `st.form()`.{FORM_DOCS_INFO}"
)
button_proto = ButtonProto()
button_proto.id = element_id
button_proto.label = label
button_proto.default = False
button_proto.is_form_submitter = is_form_submitter
button_proto.form_id = form_id
button_proto.type = type
button_proto.disabled = disabled
if help is not None:
button_proto.help = dedent(help)
if icon is not None:
button_proto.icon = validate_icon_or_emoji(icon)
if normalized_shortcut is not None:
button_proto.shortcut = normalized_shortcut
serde = ButtonSerde()
button_state = register_widget(
button_proto.id,
on_change_handler=on_click,
args=args,
kwargs=kwargs,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="trigger_value",
)
if ctx:
save_for_app_testing(ctx, element_id, button_state.value)
validate_width(width, allow_content=True)
layout_config = LayoutConfig(width=width)
self.dg._enqueue("button", button_proto, layout_config=layout_config)
return button_state.value
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
def marshall_file(
coordinates: str,
data: DownloadButtonDataType,
proto_download_button: DownloadButtonProto,
mimetype: str | None,
file_name: str | None = None,
) -> None:
# Check if data is a callable (for deferred downloads)
if callable(data):
if not runtime.exists():
# When running in "raw mode", we can't access the MediaFileManager.
proto_download_button.url = ""
return
# Register the callable for deferred execution
file_id = runtime.get_instance().media_file_mgr.add_deferred(
data,
mimetype,
coordinates,
file_name=file_name,
)
proto_download_button.deferred_file_id = file_id
proto_download_button.url = "" # No URL yet, will be generated on click
return
# Existing logic for non-callable data
data_as_bytes, inferred_mime_type = convert_data_to_bytes_and_infer_mime(
data,
unsupported_error=StreamlitAPIException(
f"Invalid binary data format: {type(data)}"
),
)
if mimetype is None:
mimetype = inferred_mime_type
if runtime.exists():
file_url = runtime.get_instance().media_file_mgr.add(
data_as_bytes,
mimetype,
coordinates,
file_name=file_name,
is_for_static_download=True,
)
else:
# When running in "raw mode", we can't access the MediaFileManager.
file_url = ""
proto_download_button.url = file_url
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/widgets/chat.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from collections.abc import Iterator, MutableMapping, Sequence
from dataclasses import dataclass, field
from enum import Enum
from typing import (
TYPE_CHECKING,
Any,
Literal,
cast,
overload,
)
from streamlit import config, runtime
from streamlit.delta_generator_singletons import get_dg_singleton_instance
from streamlit.elements.lib.file_uploader_utils import (
enforce_filename_restriction,
normalize_upload_file_type,
)
from streamlit.elements.lib.form_utils import is_in_form
from streamlit.elements.lib.image_utils import AtomicImage, image_to_url
from streamlit.elements.lib.layout_utils import (
LayoutConfig,
Width,
WidthWithoutContent,
validate_width,
)
from streamlit.elements.lib.policies import check_widget_policies
from streamlit.elements.lib.utils import (
Key,
compute_and_register_element_id,
get_chat_input_accept_file_proto_value,
save_for_app_testing,
to_key,
)
from streamlit.elements.widgets.audio_input import ALLOWED_SAMPLE_RATES
from streamlit.errors import StreamlitAPIException
from streamlit.proto.Block_pb2 import Block as BlockProto
from streamlit.proto.ChatInput_pb2 import ChatInput as ChatInputProto
from streamlit.proto.Common_pb2 import ChatInputValue as ChatInputValueProto
from streamlit.proto.Common_pb2 import FileUploaderState as FileUploaderStateProto
from streamlit.proto.Common_pb2 import UploadedFileInfo as UploadedFileInfoProto
from streamlit.proto.RootContainer_pb2 import RootContainer
from streamlit.proto.WidthConfig_pb2 import WidthConfig
from streamlit.runtime.memory_uploaded_file_manager import (
MemoryUploadedFileManager,
)
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner_utils.script_run_context import get_script_run_ctx
from streamlit.runtime.state import (
WidgetArgs,
WidgetCallback,
WidgetKwargs,
register_widget,
)
from streamlit.runtime.state.session_state_proxy import get_session_state
from streamlit.runtime.uploaded_file_manager import DeletedFile, UploadedFile
from streamlit.string_util import is_emoji, validate_material_icon
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
# Audio file validation constants
_ACCEPTED_AUDIO_EXTENSION: str = ".wav"
_ACCEPTED_AUDIO_MIME_TYPES: frozenset[str] = frozenset(
{
"audio/wav",
"audio/wave",
"audio/x-wav",
}
)
@dataclass
class ChatInputValue(MutableMapping[str, Any]):
"""Represents the value returned by `st.chat_input` after user interaction.
This dataclass contains the user's input text, any files uploaded, and optionally
an audio recording. It provides a dict-like interface for accessing and modifying
its attributes.
Attributes
----------
text : str
The text input provided by the user.
files : list[UploadedFile]
A list of files uploaded by the user. Only present when accept_file=True.
audio : UploadedFile or None, optional
An audio recording uploaded by the user, if any. Only present when accept_audio=True.
Notes
-----
- Supports dict-like access via `__getitem__`, `__setitem__`, and `__delitem__`.
- Use `to_dict()` to convert the value to a standard dictionary.
- The 'files' key is only present when accept_file=True.
- The 'audio' key is only present when accept_audio=True.
"""
text: str
files: list[UploadedFile] = field(default_factory=list)
audio: UploadedFile | None = None
_include_files: bool = field(default=False, repr=False, compare=False)
_include_audio: bool = field(default=False, repr=False, compare=False)
_included_keys: tuple[str, ...] = field(init=False, repr=False, compare=False)
def __post_init__(self) -> None:
"""Compute and cache the included keys after initialization."""
keys: list[str] = ["text"]
if self._include_files:
keys.append("files")
if self._include_audio:
keys.append("audio")
object.__setattr__(self, "_included_keys", tuple(keys))
def _get_included_keys(self) -> tuple[str, ...]:
"""Return tuple of keys that should be exposed based on inclusion flags."""
return self._included_keys
def __len__(self) -> int:
return len(self._get_included_keys())
def __iter__(self) -> Iterator[str]:
return iter(self._get_included_keys())
def __contains__(self, key: object) -> bool:
if not isinstance(key, str):
return False
return key in self._get_included_keys()
def __getitem__(self, item: str) -> str | list[UploadedFile] | UploadedFile | None:
if item not in self._get_included_keys():
raise KeyError(f"Invalid key: {item}")
try:
return getattr(self, item) # type: ignore[no-any-return]
except AttributeError:
raise KeyError(f"Invalid key: {item}") from None
def __getattribute__(self, name: str) -> Any:
# Intercept access to files/audio when they're excluded
# Use object.__getattribute__ to avoid infinite recursion
if name == "files" and not object.__getattribute__(self, "_include_files"):
raise AttributeError(
"'ChatInputValue' object has no attribute 'files' (accept_file=False)"
)
if name == "audio" and not object.__getattribute__(self, "_include_audio"):
raise AttributeError(
"'ChatInputValue' object has no attribute 'audio' (accept_audio=False)"
)
# For all other attributes, use normal lookup
return object.__getattribute__(self, name)
def __setitem__(self, key: str, value: Any) -> None:
if key not in self._get_included_keys():
raise KeyError(f"Invalid key: {key}")
setattr(self, key, value)
def __delitem__(self, key: str) -> None:
if key not in self._get_included_keys():
raise KeyError(f"Invalid key: {key}")
try:
delattr(self, key)
except AttributeError:
raise KeyError(f"Invalid key: {key}") from None
def to_dict(self) -> dict[str, str | list[UploadedFile] | UploadedFile | None]:
result: dict[str, str | list[UploadedFile] | UploadedFile | None] = {
"text": self.text
}
if self._include_files:
result["files"] = self.files
if self._include_audio:
result["audio"] = self.audio
return result
class PresetNames(str, Enum):
USER = "user"
ASSISTANT = "assistant"
AI = "ai" # Equivalent to assistant
HUMAN = "human" # Equivalent to user
def _process_avatar_input(
avatar: str | AtomicImage | None, delta_path: str
) -> tuple[BlockProto.ChatMessage.AvatarType.ValueType, str]:
"""Detects the avatar type and prepares the avatar data for the frontend.
Parameters
----------
avatar :
The avatar that was provided by the user.
delta_path : str
The delta path is used as media ID when a local image is served via the media
file manager.
Returns
-------
Tuple[AvatarType, str]
The detected avatar type and the prepared avatar data.
"""
AvatarType = BlockProto.ChatMessage.AvatarType # noqa: N806
if avatar is None:
return AvatarType.ICON, ""
if isinstance(avatar, str) and avatar in {item.value for item in PresetNames}:
# On the frontend, we only support "assistant" and "user" for the avatar.
return (
AvatarType.ICON,
(
"assistant"
if avatar in [PresetNames.AI, PresetNames.ASSISTANT]
else "user"
),
)
if isinstance(avatar, str) and is_emoji(avatar):
return AvatarType.EMOJI, avatar
if isinstance(avatar, str) and avatar.startswith(":material"):
return AvatarType.ICON, validate_material_icon(avatar)
try:
return AvatarType.IMAGE, image_to_url(
avatar,
layout_config=LayoutConfig(width="content"),
clamp=False,
channels="RGB",
output_format="auto",
image_id=delta_path,
)
except Exception as ex:
raise StreamlitAPIException(
"Failed to load the provided avatar value as an image."
) from ex
def _pop_upload_files(
files_value: FileUploaderStateProto | None,
) -> list[UploadedFile]:
if files_value is None:
return []
ctx = get_script_run_ctx()
if ctx is None:
return []
uploaded_file_info = files_value.uploaded_file_info
if len(uploaded_file_info) == 0:
return []
file_recs_list = ctx.uploaded_file_mgr.get_files(
session_id=ctx.session_id,
file_ids=[f.file_id for f in uploaded_file_info],
)
file_recs = {f.file_id: f for f in file_recs_list}
collected_files: list[UploadedFile] = []
for f in uploaded_file_info:
maybe_file_rec = file_recs.get(f.file_id)
if maybe_file_rec is not None:
uploaded_file = UploadedFile(maybe_file_rec, f.file_urls)
collected_files.append(uploaded_file)
# Remove file from manager after creating UploadedFile object.
# Only MemoryUploadedFileManager implements remove_file.
# This explicit type check ensures we only use this cleanup logic
# with manager types we've explicitly approved.
if isinstance(ctx.uploaded_file_mgr, MemoryUploadedFileManager):
ctx.uploaded_file_mgr.remove_file(
session_id=ctx.session_id,
file_id=f.file_id,
)
return collected_files
def _pop_audio_file(
audio_file_info: UploadedFileInfoProto | None,
) -> UploadedFile | None:
"""Extract and return a single audio file from the protobuf message.
Similar to _pop_upload_files but handles a single audio file instead of a list.
Validates that the uploaded file is a WAV file.
Parameters
----------
audio_file_info : UploadedFileInfoProto or None
The protobuf message containing information about the uploaded audio file.
Returns
-------
UploadedFile or None
The extracted audio file if available, None otherwise.
Raises
------
StreamlitAPIException
If the uploaded audio file does not have a `.wav` extension or its MIME type is not
one of the accepted WAV types (`audio/wav`, `audio/wave`, `audio/x-wav`).
"""
if audio_file_info is None:
return None
ctx = get_script_run_ctx()
if ctx is None:
return None
file_recs_list = ctx.uploaded_file_mgr.get_files(
session_id=ctx.session_id,
file_ids=[audio_file_info.file_id],
)
if len(file_recs_list) == 0:
return None
file_rec = file_recs_list[0]
uploaded_file = UploadedFile(file_rec, audio_file_info.file_urls)
# Validate that the file is a WAV file by checking extension and MIME type
if not uploaded_file.name.lower().endswith(_ACCEPTED_AUDIO_EXTENSION):
raise StreamlitAPIException(
f"Invalid file extension for audio input: `{uploaded_file.name}`. "
f"Only WAV files ({_ACCEPTED_AUDIO_EXTENSION}) are accepted."
)
# Validate MIME type (browsers may send different variations of WAV MIME types)
if uploaded_file.type not in _ACCEPTED_AUDIO_MIME_TYPES:
raise StreamlitAPIException(
f"Invalid MIME type for audio input: `{uploaded_file.type}`. "
f"Expected one of {_ACCEPTED_AUDIO_MIME_TYPES}."
)
# Remove the file from the manager after creating the UploadedFile object.
# Only MemoryUploadedFileManager implements remove_file (not part of the
# UploadedFileManager Protocol). This explicit type check ensures we only
# use this cleanup logic with manager types we've explicitly approved.
if audio_file_info and isinstance(ctx.uploaded_file_mgr, MemoryUploadedFileManager):
ctx.uploaded_file_mgr.remove_file(
session_id=ctx.session_id,
file_id=audio_file_info.file_id,
)
return uploaded_file
@dataclass
class ChatInputSerde:
accept_files: bool = False
accept_audio: bool = False
allowed_types: Sequence[str] | None = None
def deserialize(
self, ui_value: ChatInputValueProto | None
) -> str | ChatInputValue | None:
if ui_value is None or not ui_value.HasField("data"):
return None
if not self.accept_files and not self.accept_audio:
return ui_value.data
uploaded_files = _pop_upload_files(ui_value.file_uploader_state)
for file in uploaded_files:
if self.allowed_types and not isinstance(file, DeletedFile):
enforce_filename_restriction(file.name, self.allowed_types)
# Extract audio file separately from the audio_file_info field
audio_file = _pop_audio_file(
ui_value.audio_file_info if ui_value.HasField("audio_file_info") else None
)
return ChatInputValue(
text=ui_value.data,
files=uploaded_files,
audio=audio_file,
_include_files=self.accept_files,
_include_audio=self.accept_audio,
)
def serialize(self, v: str | None) -> ChatInputValueProto:
return ChatInputValueProto(data=v)
class ChatMixin:
@gather_metrics("chat_message")
def chat_message(
self,
name: Literal["user", "assistant", "ai", "human"] | str,
*,
avatar: Literal["user", "assistant"] | str | AtomicImage | None = None,
width: Width = "stretch",
) -> DeltaGenerator:
"""Insert a chat message container.
To add elements to the returned container, you can use ``with`` notation
(preferred) or just call methods directly on the returned object. See the
examples below.
.. note::
To follow best design practices and maintain a good appearance on
all screen sizes, don't nest chat message containers.
Parameters
----------
name : "user", "assistant", "ai", "human", or str
The name of the message author. Can be "human"/"user" or
"ai"/"assistant" to enable preset styling and avatars.
Currently, the name is not shown in the UI but is only set as an
accessibility label. For accessibility reasons, you should not use
an empty string.
avatar : Anything supported by st.image (except list), str, or None
The avatar shown next to the message.
If ``avatar`` is ``None`` (default), the icon will be determined
from ``name`` as follows:
- If ``name`` is ``"user"`` or ``"human"``, the message will have a
default user icon.
- If ``name`` is ``"ai"`` or ``"assistant"``, the message will have
a default bot icon.
- For all other values of ``name``, the message will show the first
letter of the name.
In addition to the types supported by |st.image|_ (except list),
the following strings are valid:
- A single-character emoji. For example, you can set ``avatar="🧑💻"``
or ``avatar="🦖"``. Emoji short codes are not supported.
- An icon from the Material Symbols library (rounded style) in the
format ``":material/icon_name:"`` where "icon_name" is the name
of the icon in snake case.
For example, ``icon=":material/thumb_up:"`` will display the
Thumb Up icon. Find additional icons in the `Material Symbols \
<https://fonts.google.com/icons?icon.set=Material+Symbols&icon.style=Rounded>`_
font library.
- ``"spinner"``: Displays a spinner as an icon.
.. |st.image| replace:: ``st.image``
.. _st.image: https://docs.streamlit.io/develop/api-reference/media/st.image
width : "stretch", "content", or int
The width of the chat message container. This can be one of the following:
- ``"stretch"`` (default): The width of the container matches the
width of the parent container.
- ``"content"``: The width of the container matches the width of its
content, but doesn't exceed the width of the parent container.
- An integer specifying the width in pixels: The container has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the container matches the width
of the parent container.
Returns
-------
Container
A single container that can hold multiple elements.
Examples
--------
You can use ``with`` notation to insert any element into an expander
>>> import streamlit as st
>>> import numpy as np
>>>
>>> with st.chat_message("user"):
... st.write("Hello 👋")
... st.line_chart(np.random.randn(30, 3))
.. output::
https://doc-chat-message-user.streamlit.app/
height: 450px
Or you can just call methods directly in the returned objects:
>>> import streamlit as st
>>> import numpy as np
>>>
>>> message = st.chat_message("assistant")
>>> message.write("Hello human")
>>> message.bar_chart(np.random.randn(30, 3))
.. output::
https://doc-chat-message-user1.streamlit.app/
height: 450px
"""
if name is None:
raise StreamlitAPIException(
"The author name is required for a chat message, please set it via the parameter `name`."
)
if avatar is None and (
name.lower() in {item.value for item in PresetNames} or is_emoji(name)
):
# For selected labels, we are mapping the label to an avatar
avatar = name.lower()
avatar_type, converted_avatar = _process_avatar_input(
avatar, self.dg._get_delta_path_str()
)
validate_width(width, allow_content=True)
message_container_proto = BlockProto.ChatMessage()
message_container_proto.name = name
message_container_proto.avatar = converted_avatar
message_container_proto.avatar_type = avatar_type
# Set up width configuration
width_config = WidthConfig()
if isinstance(width, int):
width_config.pixel_width = width
elif width == "content":
width_config.use_content = True
else:
width_config.use_stretch = True
block_proto = BlockProto()
block_proto.allow_empty = True
block_proto.chat_message.CopyFrom(message_container_proto)
block_proto.width_config.CopyFrom(width_config)
return self.dg._block(block_proto=block_proto)
@overload
def chat_input(
self,
placeholder: str = "Your message",
*,
key: Key | None = None,
max_chars: int | None = None,
accept_file: Literal[False] = False,
file_type: str | Sequence[str] | None = None,
accept_audio: Literal[False] = False,
disabled: bool = False,
on_submit: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
width: WidthWithoutContent = "stretch",
) -> str | None: ...
@overload
def chat_input(
self,
placeholder: str = "Your message",
*,
key: Key | None = None,
max_chars: int | None = None,
accept_file: Literal[False] = False,
file_type: str | Sequence[str] | None = None,
accept_audio: Literal[True],
audio_sample_rate: int | None = 16000,
disabled: bool = False,
on_submit: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
width: WidthWithoutContent = "stretch",
) -> ChatInputValue | None: ...
@overload
def chat_input(
self,
placeholder: str = "Your message",
*,
key: Key | None = None,
max_chars: int | None = None,
accept_file: Literal[True, "multiple", "directory"],
file_type: str | Sequence[str] | None = None,
accept_audio: bool = False,
audio_sample_rate: int | None = 16000,
disabled: bool = False,
on_submit: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
width: WidthWithoutContent = "stretch",
) -> ChatInputValue | None: ...
@gather_metrics("chat_input")
def chat_input(
self,
placeholder: str = "Your message",
*,
key: Key | None = None,
max_chars: int | None = None,
accept_file: bool | Literal["multiple", "directory"] = False,
file_type: str | Sequence[str] | None = None,
accept_audio: bool = False,
audio_sample_rate: int | None = 16000,
disabled: bool = False,
on_submit: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
width: WidthWithoutContent = "stretch",
) -> str | ChatInputValue | None:
"""Display a chat input widget.
Parameters
----------
placeholder : str
A placeholder text shown when the chat input is empty. This
defaults to ``"Your message"``. For accessibility reasons, you
should not use an empty string.
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget based on
its content. No two widgets may have the same key.
max_chars : int or None
The maximum number of characters that can be entered. If this is
``None`` (default), there will be no maximum.
accept_file : bool, "multiple", or "directory"
Whether the chat input should accept files. This can be one of the
following values:
- ``False`` (default): No files are accepted and the user can only
submit a message.
- ``True``: The user can add a single file to their submission.
- ``"multiple"``: The user can add multiple files to their
submission.
- ``"directory"``: The user can add multiple files to their
submission by selecting a directory. If ``file_type`` is set,
only files matching those type(s) will be uploaded.
By default, uploaded files are limited to 200 MB each. You can
configure this using the ``server.maxUploadSize`` config option.
For more information on how to set config options, see
|config.toml|_.
.. |config.toml| replace:: ``config.toml``
.. _config.toml: https://docs.streamlit.io/develop/api-reference/configuration/config.toml
file_type : str, Sequence[str], or None
The allowed file extension(s) for uploaded files. This can be one
of the following types:
- ``None`` (default): All file extensions are allowed.
- A string: A single file extension is allowed. For example, to
only accept CSV files, use ``"csv"``.
- A sequence of strings: Multiple file extensions are allowed. For
example, to only accept JPG/JPEG and PNG files, use
``["jpg", "jpeg", "png"]``.
.. note::
This is a best-effort check, but doesn't provide a
security guarantee against users uploading files of other types
or type extensions. The correct handling of uploaded files is
part of the app developer's responsibility.
accept_audio : bool
Whether to show an audio recording button in the chat input. This
defaults to ``False``. If this is ``True``, users can record and
submit audio messages. Recorded audio is available as an
``UploadedFile`` object with MIME type ``audio/wav``.
audio_sample_rate : int or None
The target sample rate for audio recording in Hz when
``accept_audio`` is ``True``. This defaults to ``16000``, which is
optimal for speech recognition.
The following values are supported: ``8000`` (telephone quality),
``11025``, ``16000`` (speech-recognition quality), ``22050``,
``24000``, ``32000``, ``44100``, ``48000`` (high-quality), or
``None``. If this is ``None``, the widget uses the browser's
default sample rate (typically 44100 or 48000 Hz).
disabled : bool
Whether the chat input should be disabled. This defaults to
``False``.
on_submit : callable
An optional callback invoked when the chat input's value is submitted.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
width : "stretch" or int
The width of the chat input widget. This can be one of the
following:
- ``"stretch"`` (default): The width of the widget matches the
width of the parent container.
- An integer specifying the width in pixels: The widget has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the widget matches the width
of the parent container.
Returns
-------
None, str, or dict-like
The user's submission. This is one of the following types:
- ``None``: If the user didn't submit a message, file, or audio
recording in the last rerun, the widget returns ``None``.
- A string: When the widget isn't configured to accept files or
audio recordings, and the user submitted a message in the last
rerun, the widget returns the user's message as a string.
- A dict-like object: When the widget is configured to accept files
or audio recordings, and the user submitted any content in the
last rerun, the widget returns a dict-like object.
The object always includes the ``text`` attribute, and
optionally includes ``files`` and/or ``audio`` attributes depending
on the ``accept_file`` and ``accept_audio`` parameters.
When the widget is configured to accept files or audio recordings,
and the user submitted content in the last rerun, you can access
the user's submission with key or attribute notation from the
dict-like object. This is shown in Example 3 below.
- The ``text`` attribute holds a string that is the user's message.
This is an empty string if the user only submitted one or more
files or audio recordings.
- The ``files`` attribute is only present when ``accept_file``
isn't ``False``. When present, it holds a list of
``UploadedFile`` objects. The list is empty if the user only
submitted a message or audio recording. Unlike
``st.file_uploader``, this attribute always returns a list, even
when the widget is configured to accept only one file at a time.
- The ``audio`` attribute is only present when ``accept_audio`` is
``True``. When present, it holds an ``UploadedFile`` object if
audio was recorded or ``None`` if no audio was recorded.
The ``UploadedFile`` class is a subclass of ``BytesIO`` and
therefore is "file-like". This means you can pass an instance of it
anywhere a file is expected.
Examples
--------
**Example 1: Pin the chat input widget to the bottom of your app**
When ``st.chat_input`` is used in the main body of an app, it will be
pinned to the bottom of the page.
>>> import streamlit as st
>>>
>>> prompt = st.chat_input("Say something")
>>> if prompt:
... st.write(f"User has sent the following prompt: {prompt}")
.. output::
https://doc-chat-input.streamlit.app/
height: 350px
**Example 2: Use the chat input widget inline**
The chat input can also be used inline by nesting it inside any layout
container (container, columns, tabs, sidebar, etc) or fragment. Create
chat interfaces embedded next to other content, or have multiple
chatbots!
>>> import streamlit as st
>>>
>>> with st.sidebar:
>>> messages = st.container(height=200)
>>> if prompt := st.chat_input("Say something"):
>>> messages.chat_message("user").write(prompt)
>>> messages.chat_message("assistant").write(f"Echo: {prompt}")
.. output::
https://doc-chat-input-inline.streamlit.app/
height: 350px
**Example 3: Let users upload files**
When you configure your chat input widget to allow file attachments, it
will return a dict-like object when the user sends a submission. You
can access the user's message through the ``text`` attribute of this
dictionary. You can access a list of the user's submitted file(s)
through the ``files`` attribute. Similar to ``st.session_state``, you
can use key or attribute notation.
>>> import streamlit as st
>>>
>>> prompt = st.chat_input(
>>> "Say something and/or attach an image",
>>> accept_file=True,
>>> file_type=["jpg", "jpeg", "png"],
>>> )
>>> if prompt and prompt.text:
>>> st.markdown(prompt.text)
>>> if prompt and prompt["files"]:
>>> st.image(prompt["files"][0])
.. output::
https://doc-chat-input-file-uploader.streamlit.app/
height: 350px
**Example 4: Programmatically set the text via session state**
You can use ``st.session_state`` to set the text of the chat input widget.
>>> import streamlit as st
>>>
>>> if st.button("Set Value"):
>>> st.session_state.chat_input = "Hello, world!"
>>> st.chat_input(key="chat_input")
>>> st.write("Chat input value:", st.session_state.chat_input)
.. output::
https://doc-chat-input-session-state.streamlit.app/
height: 350px
**Example 5: Enable audio recording**
You can enable audio recording by setting ``accept_audio=True``.
The ``accept_audio`` parameter works independently of ``accept_file``,
allowing you to enable audio recording with or without file uploads.
>>> import streamlit as st
>>>
>>> prompt = st.chat_input(
>>> "Say or record something",
>>> accept_audio=True,
>>> )
>>> if prompt and prompt.text:
>>> st.write("Text:", prompt.text)
>>> if prompt and prompt.audio:
>>> st.audio(prompt.audio)
>>> st.write("Audio file:", prompt.audio.name)
.. output::
https://doc-chat-input-audio.streamlit.app/
height: 350px
"""
key = to_key(key)
check_widget_policies(
self.dg,
key,
on_submit,
default_value=None,
writes_allowed=True,
)
if accept_file not in {True, False, "multiple", "directory"}:
raise StreamlitAPIException(
"The `accept_file` parameter must be a boolean or 'multiple' or 'directory'."
)
ctx = get_script_run_ctx()
element_id = compute_and_register_element_id(
"chat_input",
user_key=key,
# Treat the provided key as the main identity. Only include
# properties that can invalidate the current widget state
# when changed. For chat_input, those are:
# - accept_file: Changes whether files can be attached (and how)
# - file_type: Restricts the accepted file types
# - max_chars: Changes the maximum allowed characters for the input
key_as_main_identity={"accept_file", "file_type", "max_chars"},
dg=self.dg,
placeholder=placeholder,
max_chars=max_chars,
accept_file=accept_file,
file_type=file_type,
accept_audio=accept_audio,
audio_sample_rate=audio_sample_rate,
width=width,
)
if file_type:
file_type = normalize_upload_file_type(file_type)
# Validate audio_sample_rate if provided
if (
audio_sample_rate is not None
and audio_sample_rate not in ALLOWED_SAMPLE_RATES
):
raise StreamlitAPIException(
f"Invalid audio_sample_rate: {audio_sample_rate}. "
f"Must be one of {sorted(ALLOWED_SAMPLE_RATES)} Hz, or None for browser default."
)
# It doesn't make sense to create a chat input inside a form.
# We throw an error to warn the user about this.
# We omit this check for scripts running outside streamlit, because
# they will have no script_run_ctx.
if runtime.exists() and is_in_form(self.dg):
raise StreamlitAPIException(
"`st.chat_input()` can't be used in a `st.form()`."
)
# Determine the position of the chat input:
# Use bottom position if chat input is within the main container
# either directly or within a vertical container. If it has any
# other container types as parents, we use inline position.
ancestor_block_types = set(self.dg._active_dg._ancestor_block_types)
if (
self.dg._active_dg._root_container == RootContainer.MAIN
and not ancestor_block_types
):
position = "bottom"
else:
position = "inline"
chat_input_proto = ChatInputProto()
chat_input_proto.id = element_id
chat_input_proto.placeholder = str(placeholder)
if max_chars is not None:
chat_input_proto.max_chars = max_chars
# Setting a default value is currently not supported for chat input.
chat_input_proto.default = ""
chat_input_proto.accept_file = get_chat_input_accept_file_proto_value(
accept_file
)
chat_input_proto.file_type[:] = file_type if file_type is not None else []
chat_input_proto.max_upload_size_mb = config.get_option("server.maxUploadSize")
chat_input_proto.accept_audio = accept_audio
if audio_sample_rate is not None:
chat_input_proto.audio_sample_rate = audio_sample_rate
serde = ChatInputSerde(
accept_files=accept_file in {True, "multiple", "directory"},
accept_audio=accept_audio,
allowed_types=file_type,
)
widget_state = register_widget( # type: ignore[misc]
chat_input_proto.id,
on_change_handler=on_submit,
args=args,
kwargs=kwargs,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="chat_input_value",
)
validate_width(width)
layout_config = LayoutConfig(width=width)
chat_input_proto.disabled = disabled
if widget_state.value_changed and widget_state.value is not None:
# Support for programmatically setting the text in the chat input
# via session state. Since chat input has a trigger state,
# it works a bit differently to other widgets. We are not changing
# the actual widget state here, but only inserting the provided value
# into the chat input field. The user needs to submit the value in
# order for the chat input to reflect the value in the backend state.
chat_input_proto.value = widget_state.value
chat_input_proto.set_value = True
session_state = get_session_state()
if key is not None and key in session_state:
# Reset the session state value to None to reflect the actual state
# of the widget. Which is None since the value hasn't been submitted yet.
session_state.reset_state_value(key, None)
if ctx:
save_for_app_testing(ctx, element_id, widget_state.value)
if position == "bottom":
# We need to enqueue the chat input into the bottom container
# instead of the currently active dg.
get_dg_singleton_instance().bottom_dg._enqueue(
"chat_input", chat_input_proto, layout_config=layout_config
)
else:
self.dg._enqueue(
"chat_input", chat_input_proto, layout_config=layout_config
)
return widget_state.value if not widget_state.value_changed else None
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/widgets/slider.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from collections.abc import Sequence
from dataclasses import dataclass
from datetime import date, datetime, time, timedelta, timezone, tzinfo
from numbers import Integral, Real
from textwrap import dedent
from typing import (
TYPE_CHECKING,
Any,
Final,
TypeAlias,
TypedDict,
TypeVar,
cast,
overload,
)
from streamlit.elements.lib.form_utils import current_form_id
from streamlit.elements.lib.js_number import JSNumber, JSNumberBoundsException
from streamlit.elements.lib.layout_utils import LayoutConfig, validate_width
from streamlit.elements.lib.policies import (
check_widget_policies,
maybe_raise_label_warnings,
)
from streamlit.elements.lib.utils import (
Key,
LabelVisibility,
compute_and_register_element_id,
get_label_visibility_proto_value,
to_key,
)
from streamlit.errors import (
StreamlitAPIException,
StreamlitValueAboveMaxError,
StreamlitValueBelowMinError,
)
from streamlit.proto.Slider_pb2 import Slider as SliderProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner import ScriptRunContext, get_script_run_ctx
from streamlit.runtime.state import (
WidgetArgs,
WidgetCallback,
WidgetKwargs,
get_session_state,
register_widget,
)
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
from streamlit.elements.lib.layout_utils import WidthWithoutContent
SliderNumericT = TypeVar("SliderNumericT", int, float)
SliderDatelikeT = TypeVar("SliderDatelikeT", date, time, datetime)
SliderNumericSpanT: TypeAlias = (
list[SliderNumericT]
| tuple[()]
| tuple[SliderNumericT]
| tuple[SliderNumericT, SliderNumericT]
)
SliderDatelikeSpanT: TypeAlias = (
list[SliderDatelikeT]
| tuple[()]
| tuple[SliderDatelikeT]
| tuple[SliderDatelikeT, SliderDatelikeT]
)
StepNumericT: TypeAlias = SliderNumericT
StepDatelikeT: TypeAlias = timedelta
SliderStep: TypeAlias = int | float | timedelta
SliderScalar: TypeAlias = int | float | date | time | datetime
SliderValueT = TypeVar("SliderValueT", int, float, date, time, datetime)
SliderValueGeneric: TypeAlias = SliderValueT | Sequence[SliderValueT]
SliderValue: TypeAlias = (
SliderValueGeneric[int]
| SliderValueGeneric[float] # ty: ignore
| SliderValueGeneric[date]
| SliderValueGeneric[time]
| SliderValueGeneric[datetime]
)
SliderReturnGeneric: TypeAlias = (
SliderValueT | tuple[SliderValueT] | tuple[SliderValueT, SliderValueT]
)
SliderReturn: TypeAlias = (
SliderReturnGeneric[int]
| SliderReturnGeneric[float] # ty: ignore
| SliderReturnGeneric[date]
| SliderReturnGeneric[time]
| SliderReturnGeneric[datetime]
)
SECONDS_TO_MICROS: Final = 1000 * 1000
DAYS_TO_MICROS: Final = 24 * 60 * 60 * SECONDS_TO_MICROS
UTC_EPOCH: Final = datetime(1970, 1, 1, tzinfo=timezone.utc)
SUPPORTED_TYPES: Final = {
Integral: SliderProto.INT,
Real: SliderProto.FLOAT,
datetime: SliderProto.DATETIME,
date: SliderProto.DATE,
time: SliderProto.TIME,
}
TIMELIKE_TYPES: Final = (SliderProto.DATETIME, SliderProto.TIME, SliderProto.DATE)
def _time_to_datetime(time_: time) -> datetime:
# Note, here we pick an arbitrary date well after Unix epoch.
# This prevents pre-epoch timezone issues (https://bugs.python.org/issue36759)
# We're dropping the date from datetime later, anyway.
return datetime.combine(date(2000, 1, 1), time_)
def _date_to_datetime(date_: date) -> datetime:
return datetime.combine(date_, time())
def _delta_to_micros(delta: timedelta) -> int:
return (
delta.microseconds
+ delta.seconds * SECONDS_TO_MICROS
+ delta.days * DAYS_TO_MICROS
)
def _datetime_to_micros(dt: datetime) -> int:
# The frontend is not aware of timezones and only expects a UTC-based
# timestamp (in microseconds). Since we want to show the date/time exactly
# as it is in the given datetime object, we just set the tzinfo to UTC and
# do not do any timezone conversions. Only the backend knows about
# original timezone and will replace the UTC timestamp in the deserialization.
utc_dt = dt.replace(tzinfo=timezone.utc)
return _delta_to_micros(utc_dt - UTC_EPOCH)
def _micros_to_datetime(micros: int, orig_tz: tzinfo | None) -> datetime:
"""Restore times/datetimes to original timezone (dates are always naive)."""
utc_dt = UTC_EPOCH + timedelta(microseconds=micros)
# Add the original timezone. No conversion is required here,
# since in the serialization, we also just replace the timestamp with UTC.
return utc_dt.replace(tzinfo=orig_tz)
class SliderDefaultValues(TypedDict):
min_value: SliderScalar
max_value: SliderScalar
step: SliderStep
format: str
@dataclass
class SliderSerde:
value: list[float]
data_type: int
single_value: bool
orig_tz: tzinfo | None
def deserialize_single_value(self, value: float) -> SliderScalar:
if self.data_type == SliderProto.INT:
return int(value)
if self.data_type == SliderProto.DATETIME:
return _micros_to_datetime(int(value), self.orig_tz)
if self.data_type == SliderProto.DATE:
return _micros_to_datetime(int(value), self.orig_tz).date()
if self.data_type == SliderProto.TIME:
return (
_micros_to_datetime(int(value), self.orig_tz)
.time()
.replace(tzinfo=self.orig_tz)
)
return value
def deserialize(self, ui_value: list[float] | None) -> Any:
if ui_value is not None:
val = ui_value
else:
# Widget has not been used; fallback to the original value,
val = self.value
# The widget always returns a float array, so fix the return type if necessary
deserialized_values = [self.deserialize_single_value(v) for v in val]
return (
deserialized_values[0] if self.single_value else tuple(deserialized_values)
)
def serialize(self, v: Any) -> list[Any]:
range_value = isinstance(v, (list, tuple))
# Convert to list to handle tuples
processed_value = list(v) if range_value else [v]
if self.data_type == SliderProto.DATE:
return [
_datetime_to_micros(_date_to_datetime(val)) for val in processed_value
]
if self.data_type == SliderProto.TIME:
return [
_datetime_to_micros(_time_to_datetime(val)) for val in processed_value
]
if self.data_type == SliderProto.DATETIME:
return [_datetime_to_micros(val) for val in processed_value]
# For numeric types, ensure they are floats if not already
return [float(val) for val in processed_value]
class SliderMixin:
# If min/max/value/step are not provided, then we return an int.
# if ONLY step is provided, then it must be an int and we return an int.
@overload
def slider(
self,
label: str,
min_value: None = None,
max_value: None = None,
value: None = None,
step: int | None = None,
format: str | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> int: ...
# If min-value or max_value is provided and a numeric type, and value (if provided)
# is a singular numeric, return the same numeric type.
@overload
def slider(
self,
label: str,
min_value: SliderNumericT | None = None,
max_value: SliderNumericT | None = None,
value: SliderNumericT | None = None,
step: StepNumericT[SliderNumericT] | None = None,
format: str | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> SliderNumericT: ...
# If value is provided and a sequence of numeric type,
# return a tuple of the same numeric type.
@overload
def slider(
self,
label: str,
min_value: SliderNumericT | None = None,
max_value: SliderNumericT | None = None,
*,
value: SliderNumericSpanT[SliderNumericT],
step: StepNumericT[SliderNumericT] | None = None,
format: str | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> tuple[SliderNumericT, SliderNumericT]: ...
# If value is provided positionally and a sequence of numeric type,
# return a tuple of the same numeric type.
@overload
def slider(
self,
label: str,
min_value: SliderNumericT,
max_value: SliderNumericT,
value: SliderNumericSpanT[SliderNumericT],
step: StepNumericT[SliderNumericT] | None = None,
format: str | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> tuple[SliderNumericT, SliderNumericT]: ...
# If min-value is provided and a datelike type, and value (if provided)
# is a singular datelike, return the same datelike type.
@overload
def slider(
self,
label: str,
min_value: SliderDatelikeT,
max_value: SliderDatelikeT | None = None,
value: SliderDatelikeT | None = None,
step: StepDatelikeT | None = None,
format: str | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> SliderDatelikeT: ...
# If max-value is provided and a datelike type, and value (if provided)
# is a singular datelike, return the same datelike type.
@overload
def slider(
self,
label: str,
min_value: None = None,
*,
max_value: SliderDatelikeT,
value: SliderDatelikeT | None = None,
step: StepDatelikeT | None = None,
format: str | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> SliderDatelikeT: ...
# If value is provided and a datelike type, return the same datelike type.
@overload
def slider(
self,
label: str,
min_value: None = None,
max_value: None = None,
*,
value: SliderDatelikeT,
step: StepDatelikeT | None = None,
format: str | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> SliderDatelikeT: ...
# If value is provided and a sequence of datelike type,
# return a tuple of the same datelike type.
@overload
def slider(
self,
label: str,
min_value: SliderDatelikeT | None = None,
max_value: SliderDatelikeT | None = None,
*,
value: list[SliderDatelikeT]
| tuple[SliderDatelikeT]
| tuple[SliderDatelikeT, SliderDatelikeT],
step: StepDatelikeT | None = None,
format: str | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> tuple[SliderDatelikeT, SliderDatelikeT]: ...
# If value is provided positionally and a sequence of datelike type,
# return a tuple of the same datelike type.
@overload
def slider(
self,
label: str,
min_value: SliderDatelikeT,
max_value: SliderDatelikeT,
value: SliderDatelikeSpanT[SliderDatelikeT],
/,
step: StepDatelikeT | None = None,
format: str | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> tuple[SliderDatelikeT, SliderDatelikeT]: ...
# https://github.com/python/mypy/issues/17614
@gather_metrics("slider") # type: ignore[misc]
def slider(
self,
label: str,
min_value: SliderScalar | None = None,
max_value: SliderScalar | None = None,
value: SliderValue | None = None,
step: SliderStep | None = None,
format: str | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> Any:
r"""Display a slider widget.
This supports int, float, date, time, and datetime types.
This also allows you to render a range slider by passing a two-element
tuple or list as the ``value``.
The difference between ``st.slider`` and ``st.select_slider`` is that
``slider`` only accepts numerical or date/time data and takes a range as
input, while ``select_slider`` accepts any datatype and takes an iterable
set of options.
.. note::
Integer values exceeding +/- ``(1<<53) - 1`` cannot be accurately
stored or returned by the widget due to serialization constraints
between the Python server and JavaScript client. You must handle
such numbers as floats, leading to a loss in precision.
Parameters
----------
label : str
A short label explaining to the user what this slider is for.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
For accessibility reasons, you should never set an empty label, but
you can hide it with ``label_visibility`` if needed. In the future,
we may disallow empty labels by raising an exception.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
min_value : a supported type or None
The minimum permitted value.
If this is ``None`` (default), the minimum value depends on the
type as follows:
- integer: ``0``
- float: ``0.0``
- date or datetime: ``value - timedelta(days=14)``
- time: ``time.min``
max_value : a supported type or None
The maximum permitted value.
If this is ``None`` (default), the maximum value depends on the
type as follows:
- integer: ``100``
- float: ``1.0``
- date or datetime: ``value + timedelta(days=14)``
- time: ``time.max``
value : a supported type or a tuple/list of supported types or None
The value of the slider when it first renders. If a tuple/list
of two values is passed here, then a range slider with those lower
and upper bounds is rendered. For example, if set to `(1, 10)` the
slider will have a selectable range between 1 and 10.
This defaults to ``min_value``. If the type is not otherwise
specified in any of the numeric parameters, the widget will have an
integer value.
step : int, float, timedelta, or None
The stepping interval.
Defaults to 1 if the value is an int, 0.01 if a float,
timedelta(days=1) if a date/datetime, timedelta(minutes=15) if a time
(or if max_value - min_value < 1 day)
format : str or None
A printf-style format string controlling how the interface should
display numbers. This does not impact the return value.
For information about formatting integers and floats, see
`sprintf.js
<https://github.com/alexei/sprintf.js?tab=readme-ov-file#format-specification>`_.
For example, ``format="%0.1f"`` adjusts the displayed decimal
precision to only show one digit after the decimal.
For information about formatting datetimes, dates, and times, see
`momentJS <https://momentjs.com/docs/#/displaying/format/>`_.
For example, ``format="ddd ha"`` adjusts the displayed datetime to
show the day of the week and the hour ("Tue 8pm").
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. No two widgets may have the same key.
help : str or None
A tooltip that gets displayed next to the widget label. Streamlit
only displays the tooltip when ``label_visibility="visible"``. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
on_change : callable
An optional callback invoked when this slider's value changes.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
disabled : bool
An optional boolean that disables the slider if set to ``True``.
The default is ``False``.
label_visibility : "visible", "hidden", or "collapsed"
The visibility of the label. The default is ``"visible"``. If this
is ``"hidden"``, Streamlit displays an empty spacer instead of the
label, which can help keep the widget aligned with other widgets.
If this is ``"collapsed"``, Streamlit displays no label or spacer.
width : "stretch" or int
The width of the slider widget. This can be one of the
following:
- ``"stretch"`` (default): The width of the widget matches the
width of the parent container.
- An integer specifying the width in pixels: The widget has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the widget matches the width
of the parent container.
Returns
-------
int/float/date/time/datetime or tuple of int/float/date/time/datetime
The current value of the slider widget. The return type will match
the data type of the value parameter.
Examples
--------
>>> import streamlit as st
>>>
>>> age = st.slider("How old are you?", 0, 130, 25)
>>> st.write("I'm ", age, "years old")
And here's an example of a range slider:
>>> import streamlit as st
>>>
>>> values = st.slider("Select a range of values", 0.0, 100.0, (25.0, 75.0))
>>> st.write("Values:", values)
This is a range time slider:
>>> import streamlit as st
>>> from datetime import time
>>>
>>> appointment = st.slider(
... "Schedule your appointment:", value=(time(11, 30), time(12, 45))
... )
>>> st.write("You're scheduled for:", appointment)
Finally, a datetime slider:
>>> import streamlit as st
>>> from datetime import datetime
>>>
>>> start_time = st.slider(
... "When do you start?",
... value=datetime(2020, 1, 1, 9, 30),
... format="MM/DD/YY - hh:mm",
... )
>>> st.write("Start time:", start_time)
.. output::
https://doc-slider.streamlit.app/
height: 300px
"""
ctx = get_script_run_ctx()
return self._slider(
label=label,
min_value=min_value,
max_value=max_value,
value=value,
step=step,
format=format,
key=key,
help=help,
on_change=on_change,
args=args,
kwargs=kwargs,
disabled=disabled,
label_visibility=label_visibility,
width=width,
ctx=ctx,
)
def _slider(
self,
label: str,
min_value: Any = None,
max_value: Any = None,
value: Any = None,
step: Any = None,
format: str | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
ctx: ScriptRunContext | None = None,
) -> SliderReturn:
key = to_key(key)
check_widget_policies(
self.dg,
key,
on_change,
default_value=value,
)
maybe_raise_label_warnings(label, label_visibility)
element_id = compute_and_register_element_id(
"slider",
user_key=key,
# Treat the provided key as the main identity; only include
# changes to the value-shaping arguments in the identity
# computation as those can invalidate the current value.
key_as_main_identity={"min_value", "max_value", "step"},
dg=self.dg,
label=label,
min_value=min_value,
max_value=max_value,
value=value,
step=step,
format=format,
help=help,
width=width,
)
if value is None:
# We need to know if this is a single or range slider, but don't have
# a default value, so we check if session_state can tell us.
# We already calculated the id, so there is no risk of this causing
# the id to change.
single_value = True
session_state = get_session_state().filtered_state
if key is not None and key in session_state:
state_value = session_state[key]
single_value = isinstance(state_value, tuple(SUPPORTED_TYPES.keys()))
if single_value:
value = min_value if min_value is not None else 0
else:
mn = min_value if min_value is not None else 0
mx = max_value if max_value is not None else 100
value = [mn, mx]
# Ensure that the value is either a single value or a range of values.
single_value = isinstance(value, tuple(SUPPORTED_TYPES.keys()))
range_value = isinstance(value, (list, tuple)) and len(value) in (0, 1, 2)
if not single_value and not range_value:
raise StreamlitAPIException(
"Slider value should either be an int/float/datetime or a list/tuple of "
"0 to 2 ints/floats/datetimes"
)
# Simplify future logic by always making value a list
prepared_value: Sequence[SliderScalar] = [value] if single_value else value # ty: ignore[invalid-assignment]
def value_to_generic_type(v: Any) -> SliderProto.DataType.ValueType:
if isinstance(v, Integral):
return SUPPORTED_TYPES[Integral]
if isinstance(v, Real):
return SUPPORTED_TYPES[Real]
return SUPPORTED_TYPES[type(v)]
def all_same_type(items: Any) -> bool:
return len(set(map(value_to_generic_type, items))) < 2
if not all_same_type(prepared_value):
raise StreamlitAPIException(
"Slider tuple/list components must be of the same type.\n"
f"But were: {list(map(type, prepared_value))}"
)
data_type = (
SliderProto.INT
if len(prepared_value) == 0
else value_to_generic_type(prepared_value[0])
)
datetime_min: datetime | time = time.min
datetime_max: datetime | time = time.max
if data_type == SliderProto.TIME:
prepared_value = cast("Sequence[time]", prepared_value)
datetime_min = time.min.replace(tzinfo=prepared_value[0].tzinfo)
datetime_max = time.max.replace(tzinfo=prepared_value[0].tzinfo)
if data_type in (SliderProto.DATETIME, SliderProto.DATE):
prepared_value = cast("Sequence[datetime]", prepared_value)
datetime_min = prepared_value[0] - timedelta(days=14)
datetime_max = prepared_value[0] + timedelta(days=14)
defaults: Final[dict[SliderProto.DataType.ValueType, dict[str, Any]]] = {
SliderProto.INT: {
"min_value": 0,
"max_value": 100,
"step": 1,
"format": "%d",
},
SliderProto.FLOAT: {
"min_value": 0.0,
"max_value": 1.0,
"step": 0.01,
"format": "%0.2f",
},
SliderProto.DATETIME: {
"min_value": datetime_min,
"max_value": datetime_max,
"step": timedelta(days=1),
"format": "YYYY-MM-DD",
},
SliderProto.DATE: {
"min_value": datetime_min,
"max_value": datetime_max,
"step": timedelta(days=1),
"format": "YYYY-MM-DD",
},
SliderProto.TIME: {
"min_value": datetime_min,
"max_value": datetime_max,
"step": timedelta(minutes=15),
"format": "HH:mm",
},
}
if min_value is None:
min_value = defaults[data_type]["min_value"]
if max_value is None:
max_value = defaults[data_type]["max_value"]
if step is None:
step = defaults[data_type]["step"]
if data_type in (
SliderProto.DATETIME,
SliderProto.DATE,
) and max_value - min_value < timedelta(days=1): # ty: ignore[unsupported-operator]
step = timedelta(minutes=15)
if format is None:
format = cast("str", defaults[data_type]["format"]) # noqa: A001
if step == 0:
raise StreamlitAPIException(
"Slider components cannot be passed a `step` of 0."
)
# Ensure that all arguments are of the same type.
slider_args = [min_value, max_value, step]
int_args = all(isinstance(a, Integral) for a in slider_args)
float_args = all(
isinstance(a, Real) and not isinstance(a, Integral) for a in slider_args
)
# When min and max_value are the same timelike, step should be a timedelta
timelike_args = (
data_type in TIMELIKE_TYPES
and isinstance(step, timedelta)
and type(min_value) is type(max_value)
)
if not int_args and not float_args and not timelike_args:
msg = (
"Slider value arguments must be of matching types."
f"\n`min_value` has {type(min_value).__name__} type."
f"\n`max_value` has {type(max_value).__name__} type."
f"\n`step` has {type(step).__name__} type."
)
raise StreamlitAPIException(msg)
# Ensure that the value matches arguments' types.
all_ints = data_type == SliderProto.INT and int_args
all_floats = data_type == SliderProto.FLOAT and float_args
all_timelikes = data_type in TIMELIKE_TYPES and timelike_args
if not all_ints and not all_floats and not all_timelikes:
msg = (
"Both value and arguments must be of the same type."
f"\n`value` has {type(value).__name__} type."
f"\n`min_value` has {type(min_value).__name__} type."
f"\n`max_value` has {type(max_value).__name__} type."
)
raise StreamlitAPIException(msg)
# Ensure that min <= value(s) <= max, adjusting the bounds as necessary.
min_value = min(min_value, max_value)
max_value = max(min_value, max_value)
if len(prepared_value) == 1:
min_value = min(prepared_value[0], min_value)
max_value = max(prepared_value[0], max_value)
elif len(prepared_value) == 2:
start, end = prepared_value
if start > end: # type: ignore[operator]
# Swap start and end, since they seem reversed
start, end = end, start
prepared_value = start, end
min_value = min(start, min_value)
max_value = max(end, max_value)
else:
# Empty list, so let's just use the outer bounds
prepared_value = [min_value, max_value]
# Bounds checks. JSNumber produces human-readable exceptions that
# we simply re-package as StreamlitAPIExceptions.
# (We check `min_value` and `max_value` here; `value` and `step` are
# already known to be in the [min_value, max_value] range.)
try:
if all_ints:
JSNumber.validate_int_bounds(min_value, "`min_value`")
JSNumber.validate_int_bounds(max_value, "`max_value`")
elif all_floats:
JSNumber.validate_float_bounds(min_value, "`min_value`")
JSNumber.validate_float_bounds(max_value, "`max_value`")
elif all_timelikes:
# No validation yet. TODO: check between 0001-01-01 to 9999-12-31
pass
except JSNumberBoundsException as e:
raise StreamlitAPIException(str(e))
orig_tz = None
# Convert dates or times into datetimes
if data_type == SliderProto.TIME:
prepared_value = cast("Sequence[time]", prepared_value)
min_value = cast("time", min_value)
max_value = cast("time", max_value)
prepared_value = list(map(_time_to_datetime, prepared_value))
min_value = _time_to_datetime(min_value)
max_value = _time_to_datetime(max_value)
if data_type == SliderProto.DATE:
prepared_value = cast("Sequence[date]", prepared_value)
min_value = cast("date", min_value)
max_value = cast("date", max_value)
prepared_value = list(map(_date_to_datetime, prepared_value))
min_value = _date_to_datetime(min_value)
max_value = _date_to_datetime(max_value)
# The frontend will error if the values are equal, so checking here
# lets us produce a nicer python error message and stack trace.
if min_value == max_value:
raise StreamlitAPIException(
"Slider `min_value` must be less than the `max_value`."
f"\nThe values were {min_value} and {max_value}."
)
# Now, convert to microseconds (so we can serialize datetime to a long)
if data_type in TIMELIKE_TYPES:
prepared_value = cast("Sequence[datetime]", prepared_value)
min_value = cast("datetime", min_value)
max_value = cast("datetime", max_value)
step = cast("timedelta", step)
# Restore times/datetimes to original timezone (dates are always naive)
orig_tz = (
prepared_value[0].tzinfo
if data_type in (SliderProto.TIME, SliderProto.DATETIME)
else None
)
prepared_value = list(map(_datetime_to_micros, prepared_value))
min_value = _datetime_to_micros(min_value)
max_value = _datetime_to_micros(max_value)
step = _delta_to_micros(step)
# At this point, prepared_value is expected to be a list of floats:
prepared_value = cast("list[float]", prepared_value)
# It would be great if we could guess the number of decimal places from
# the `step` argument, but this would only be meaningful if step were a
# decimal. As a possible improvement we could make this function accept
# decimals and/or use some heuristics for floats.
slider_proto = SliderProto()
slider_proto.type = SliderProto.Type.SLIDER
slider_proto.id = element_id
slider_proto.label = label
slider_proto.format = format
slider_proto.default[:] = prepared_value
slider_proto.min = min_value
slider_proto.max = max_value
slider_proto.step = cast("float", step)
slider_proto.data_type = data_type
slider_proto.options[:] = []
slider_proto.form_id = current_form_id(self.dg)
slider_proto.disabled = disabled
slider_proto.label_visibility.value = get_label_visibility_proto_value(
label_visibility
)
if help is not None:
slider_proto.help = dedent(help)
serde = SliderSerde(
prepared_value,
data_type,
single_value,
orig_tz,
)
widget_state = register_widget(
slider_proto.id,
on_change_handler=on_change,
args=args,
kwargs=kwargs,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="double_array_value",
)
if widget_state.value_changed:
# Min/Max bounds checks when the value is updated.
serialized_values = serde.serialize(widget_state.value)
for serialized_value in serialized_values:
# Use the deserialized values for more readable error messages for dates/times
deserialized_value = serde.deserialize_single_value(serialized_value)
if serialized_value < slider_proto.min:
raise StreamlitValueBelowMinError(
value=deserialized_value,
min_value=serde.deserialize_single_value(slider_proto.min),
)
if serialized_value > slider_proto.max:
raise StreamlitValueAboveMaxError(
value=deserialized_value,
max_value=serde.deserialize_single_value(slider_proto.max),
)
slider_proto.value[:] = serialized_values
slider_proto.set_value = True
validate_width(width)
layout_config = LayoutConfig(width=width)
self.dg._enqueue("slider", slider_proto, layout_config=layout_config)
return cast("SliderReturn", widget_state.value)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/widgets/camera_input.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from dataclasses import dataclass
from textwrap import dedent
from typing import TYPE_CHECKING, TypeAlias, cast
from streamlit.elements.lib.file_uploader_utils import enforce_filename_restriction
from streamlit.elements.lib.form_utils import current_form_id
from streamlit.elements.lib.layout_utils import LayoutConfig, validate_width
from streamlit.elements.lib.policies import (
check_widget_policies,
maybe_raise_label_warnings,
)
from streamlit.elements.lib.utils import (
Key,
LabelVisibility,
compute_and_register_element_id,
get_label_visibility_proto_value,
to_key,
)
from streamlit.elements.widgets.file_uploader import _get_upload_files
from streamlit.proto.CameraInput_pb2 import CameraInput as CameraInputProto
from streamlit.proto.Common_pb2 import FileUploaderState as FileUploaderStateProto
from streamlit.proto.Common_pb2 import UploadedFileInfo as UploadedFileInfoProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner import ScriptRunContext, get_script_run_ctx
from streamlit.runtime.state import (
WidgetArgs,
WidgetCallback,
WidgetKwargs,
register_widget,
)
from streamlit.runtime.uploaded_file_manager import DeletedFile, UploadedFile
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
from streamlit.elements.lib.layout_utils import WidthWithoutContent
SomeUploadedSnapshotFile: TypeAlias = UploadedFile | DeletedFile | None
@dataclass
class CameraInputSerde:
def serialize(
self,
snapshot: SomeUploadedSnapshotFile,
) -> FileUploaderStateProto:
state_proto = FileUploaderStateProto()
if snapshot is None or isinstance(snapshot, DeletedFile):
return state_proto
file_info: UploadedFileInfoProto = state_proto.uploaded_file_info.add()
file_info.file_id = snapshot.file_id
file_info.name = snapshot.name
file_info.size = snapshot.size
file_info.file_urls.CopyFrom(snapshot._file_urls)
return state_proto
def deserialize(
self, ui_value: FileUploaderStateProto | None
) -> SomeUploadedSnapshotFile:
upload_files = _get_upload_files(ui_value)
return_value = None if len(upload_files) == 0 else upload_files[0]
if return_value is not None and not isinstance(return_value, DeletedFile):
enforce_filename_restriction(return_value.name, [".jpg"])
return return_value
class CameraInputMixin:
@gather_metrics("camera_input")
def camera_input(
self,
label: str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
) -> UploadedFile | None:
r"""Display a widget that returns pictures from the user's webcam.
Parameters
----------
label : str
A short label explaining to the user what this widget is used for.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
For accessibility reasons, you should never set an empty label, but
you can hide it with ``label_visibility`` if needed. In the future,
we may disallow empty labels by raising an exception.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. No two widgets may have the same key.
help : str or None
A tooltip that gets displayed next to the widget label. Streamlit
only displays the tooltip when ``label_visibility="visible"``. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
on_change : callable
An optional callback invoked when this camera_input's value
changes.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
disabled : bool
An optional boolean that disables the camera input if set to
``True``. Default is ``False``.
label_visibility : "visible", "hidden", or "collapsed"
The visibility of the label. The default is ``"visible"``. If this
is ``"hidden"``, Streamlit displays an empty spacer instead of the
label, which can help keep the widget aligned with other widgets.
If this is ``"collapsed"``, Streamlit displays no label or spacer.
width : "stretch" or int
The width of the camera input widget. This can be one of the
following:
- ``"stretch"`` (default): The width of the widget matches the
width of the parent container.
- An integer specifying the width in pixels: The widget has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the widget matches the width
of the parent container.
Returns
-------
None or UploadedFile
The UploadedFile class is a subclass of BytesIO, and therefore is
"file-like". This means you can pass an instance of it anywhere a
file is expected.
Examples
--------
>>> import streamlit as st
>>>
>>> enable = st.checkbox("Enable camera")
>>> picture = st.camera_input("Take a picture", disabled=not enable)
>>>
>>> if picture:
... st.image(picture)
.. output::
https://doc-camera-input.streamlit.app/
height: 600px
"""
ctx = get_script_run_ctx()
return self._camera_input(
label=label,
key=key,
help=help,
on_change=on_change,
args=args,
kwargs=kwargs,
disabled=disabled,
label_visibility=label_visibility,
width=width,
ctx=ctx,
)
def _camera_input(
self,
label: str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: WidthWithoutContent = "stretch",
ctx: ScriptRunContext | None = None,
) -> UploadedFile | None:
key = to_key(key)
check_widget_policies(
self.dg,
key,
on_change,
default_value=None,
writes_allowed=False,
)
maybe_raise_label_warnings(label, label_visibility)
element_id = compute_and_register_element_id(
"camera_input",
user_key=key,
key_as_main_identity=True,
dg=self.dg,
label=label,
help=help,
width=width,
)
camera_input_proto = CameraInputProto()
camera_input_proto.id = element_id
camera_input_proto.label = label
camera_input_proto.form_id = current_form_id(self.dg)
camera_input_proto.disabled = disabled
camera_input_proto.label_visibility.value = get_label_visibility_proto_value(
label_visibility
)
if help is not None:
camera_input_proto.help = dedent(help)
validate_width(width)
layout_config = LayoutConfig(width=width)
serde = CameraInputSerde()
camera_input_state = register_widget(
camera_input_proto.id,
on_change_handler=on_change,
args=args,
kwargs=kwargs,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="file_uploader_state_value",
)
self.dg._enqueue(
"camera_input", camera_input_proto, layout_config=layout_config
)
if isinstance(camera_input_state.value, DeletedFile):
return None
return camera_input_state.value
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/widgets/checkbox.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from dataclasses import dataclass
from textwrap import dedent
from typing import TYPE_CHECKING, cast
from streamlit.elements.lib.form_utils import current_form_id
from streamlit.elements.lib.layout_utils import (
LayoutConfig,
Width,
validate_width,
)
from streamlit.elements.lib.policies import (
check_widget_policies,
maybe_raise_label_warnings,
)
from streamlit.elements.lib.utils import (
Key,
LabelVisibility,
compute_and_register_element_id,
get_label_visibility_proto_value,
to_key,
)
from streamlit.proto.Checkbox_pb2 import Checkbox as CheckboxProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner import ScriptRunContext, get_script_run_ctx
from streamlit.runtime.state import (
WidgetArgs,
WidgetCallback,
WidgetKwargs,
register_widget,
)
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
@dataclass
class CheckboxSerde:
value: bool
def serialize(self, v: bool) -> bool:
return bool(v)
def deserialize(self, ui_value: bool | None) -> bool:
return bool(ui_value if ui_value is not None else self.value)
class CheckboxMixin:
@gather_metrics("checkbox")
def checkbox(
self,
label: str,
value: bool = False,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: Width = "content",
) -> bool:
r"""Display a checkbox widget.
Parameters
----------
label : str
A short label explaining to the user what this checkbox is for.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
For accessibility reasons, you should never set an empty label, but
you can hide it with ``label_visibility`` if needed. In the future,
we may disallow empty labels by raising an exception.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
value : bool
Preselect the checkbox when it first renders. This will be
cast to bool internally.
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. No two widgets may have the same key.
help : str or None
A tooltip that gets displayed next to the widget label. Streamlit
only displays the tooltip when ``label_visibility="visible"``. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
on_change : callable
An optional callback invoked when this checkbox's value changes.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
disabled : bool
An optional boolean that disables the checkbox if set to ``True``.
The default is ``False``.
label_visibility : "visible", "hidden", or "collapsed"
The visibility of the label. The default is ``"visible"``. If this
is ``"hidden"``, Streamlit displays an empty spacer instead of the
label, which can help keep the widget aligned with other widgets.
If this is ``"collapsed"``, Streamlit displays no label or spacer.
width : "content", "stretch", or int
The width of the checkbox widget. This can be one of the following:
- ``"content"`` (default): The width of the widget matches the
width of its content, but doesn't exceed the width of the parent
container.
- ``"stretch"``: The width of the widget matches the width of the
parent container.
- An integer specifying the width in pixels: The widget has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the widget matches the width
of the parent container.
Returns
-------
bool
Whether or not the checkbox is checked.
Example
-------
>>> import streamlit as st
>>>
>>> agree = st.checkbox("I agree")
>>>
>>> if agree:
... st.write("Great!")
.. output::
https://doc-checkbox.streamlit.app/
height: 220px
"""
ctx = get_script_run_ctx()
return self._checkbox(
label=label,
value=value,
key=key,
help=help,
on_change=on_change,
args=args,
kwargs=kwargs,
disabled=disabled,
label_visibility=label_visibility,
type=CheckboxProto.StyleType.DEFAULT,
ctx=ctx,
width=width,
)
@gather_metrics("toggle")
def toggle(
self,
label: str,
value: bool = False,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: Width = "content",
) -> bool:
r"""Display a toggle widget.
Parameters
----------
label : str
A short label explaining to the user what this toggle is for.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
For accessibility reasons, you should never set an empty label, but
you can hide it with ``label_visibility`` if needed. In the future,
we may disallow empty labels by raising an exception.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
value : bool
Preselect the toggle when it first renders. This will be
cast to bool internally.
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. No two widgets may have the same key.
help : str or None
A tooltip that gets displayed next to the widget label. Streamlit
only displays the tooltip when ``label_visibility="visible"``. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
on_change : callable
An optional callback invoked when this toggle's value changes.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
disabled : bool
An optional boolean that disables the toggle if set to ``True``.
The default is ``False``.
label_visibility : "visible", "hidden", or "collapsed"
The visibility of the label. The default is ``"visible"``. If this
is ``"hidden"``, Streamlit displays an empty spacer instead of the
label, which can help keep the widget aligned with other widgets.
If this is ``"collapsed"``, Streamlit displays no label or spacer.
width : "content", "stretch", or int
The width of the toggle widget. This can be one of the following:
- ``"content"`` (default): The width of the widget matches the
width of its content, but doesn't exceed the width of the parent
container.
- ``"stretch"``: The width of the widget matches the width of the
parent container.
- An integer specifying the width in pixels: The widget has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the widget matches the width
of the parent container.
Returns
-------
bool
Whether or not the toggle is checked.
Example
-------
>>> import streamlit as st
>>>
>>> on = st.toggle("Activate feature")
>>>
>>> if on:
... st.write("Feature activated!")
.. output::
https://doc-toggle.streamlit.app/
height: 220px
"""
ctx = get_script_run_ctx()
return self._checkbox(
label=label,
value=value,
key=key,
help=help,
on_change=on_change,
args=args,
kwargs=kwargs,
disabled=disabled,
label_visibility=label_visibility,
type=CheckboxProto.StyleType.TOGGLE,
ctx=ctx,
width=width,
)
def _checkbox(
self,
label: str,
value: bool = False,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
type: CheckboxProto.StyleType.ValueType = CheckboxProto.StyleType.DEFAULT,
ctx: ScriptRunContext | None = None,
width: Width = "content",
) -> bool:
key = to_key(key)
check_widget_policies(
self.dg,
key,
on_change,
default_value=None if value is False else value,
)
maybe_raise_label_warnings(label, label_visibility)
element_id = compute_and_register_element_id(
"toggle" if type == CheckboxProto.StyleType.TOGGLE else "checkbox",
user_key=key,
key_as_main_identity=True,
dg=self.dg,
label=label,
value=bool(value),
help=help,
width=width,
)
checkbox_proto = CheckboxProto()
checkbox_proto.id = element_id
checkbox_proto.label = label
checkbox_proto.default = bool(value)
checkbox_proto.type = type
checkbox_proto.form_id = current_form_id(self.dg)
checkbox_proto.disabled = disabled
checkbox_proto.label_visibility.value = get_label_visibility_proto_value(
label_visibility
)
if help is not None:
checkbox_proto.help = dedent(help)
validate_width(width, allow_content=True)
layout_config = LayoutConfig(width=width)
serde = CheckboxSerde(value)
checkbox_state = register_widget(
checkbox_proto.id,
on_change_handler=on_change,
args=args,
kwargs=kwargs,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="bool_value",
)
if checkbox_state.value_changed:
checkbox_proto.value = checkbox_state.value
checkbox_proto.set_value = True
self.dg._enqueue("checkbox", checkbox_proto, layout_config=layout_config)
return checkbox_state.value
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/widgets/button_group.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from collections.abc import Callable, Sequence
from dataclasses import dataclass, field
from typing import (
TYPE_CHECKING,
Any,
Final,
Generic,
Literal,
TypeAlias,
TypeVar,
cast,
overload,
)
from streamlit import config
from streamlit.elements.lib.form_utils import current_form_id
from streamlit.elements.lib.layout_utils import (
LayoutConfig,
Width,
validate_width,
)
from streamlit.elements.lib.options_selector_utils import (
check_and_convert_to_indices,
convert_to_sequence_and_check_comparable,
get_default_indices,
)
from streamlit.elements.lib.policies import (
check_widget_policies,
maybe_raise_label_warnings,
)
from streamlit.elements.lib.utils import (
Key,
LabelVisibility,
compute_and_register_element_id,
get_label_visibility_proto_value,
save_for_app_testing,
to_key,
)
from streamlit.errors import StreamlitAPIException
from streamlit.proto.ButtonGroup_pb2 import ButtonGroup as ButtonGroupProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner_utils.script_run_context import get_script_run_ctx
from streamlit.runtime.state import register_widget
from streamlit.string_util import is_emoji, validate_material_icon
if TYPE_CHECKING:
from streamlit.dataframe_util import OptionSequence
from streamlit.delta_generator import DeltaGenerator
from streamlit.runtime.state import (
WidgetArgs,
WidgetCallback,
WidgetKwargs,
)
from streamlit.runtime.state.common import (
RegisterWidgetResult,
WidgetDeserializer,
WidgetSerializer,
)
T = TypeVar("T")
V = TypeVar("V")
_THUMB_ICONS: Final = (":material/thumb_up:", ":material/thumb_down:")
_FACES_ICONS: Final = (
":material/sentiment_sad:",
":material/sentiment_dissatisfied:",
":material/sentiment_neutral:",
":material/sentiment_satisfied:",
":material/sentiment_very_satisfied:",
)
_NUMBER_STARS: Final = 5
_STAR_ICON: Final = ":material/star:"
# we don't have the filled-material icon library as a dependency. Hence, we have it here
# in base64 format and send it over the wire as an image.
_SELECTED_STAR_ICON: Final = ":material/star_filled:"
SelectionMode: TypeAlias = Literal["single", "multi"]
@dataclass
class _MultiSelectSerde(Generic[T]):
"""Only meant to be used internally for the button_group element.
This serde is inspired by the MultiSelectSerde from multiselect.py. That serde has
been updated since then to support the accept_new_options parameter, which is not
required by the button_group element. If this changes again at some point,
the two elements can share the same serde again.
"""
options: Sequence[T]
default_value: list[int] = field(default_factory=list)
def serialize(self, value: list[T]) -> list[int]:
indices = check_and_convert_to_indices(self.options, value)
return indices if indices is not None else []
def deserialize(self, ui_value: list[int] | None) -> list[T]:
current_value: list[int] = (
ui_value if ui_value is not None else self.default_value
)
return [self.options[i] for i in current_value]
class _SingleSelectSerde(Generic[T]):
"""Only meant to be used internally for the button_group element.
Uses the ButtonGroup's _MultiSelectSerde under-the-hood, but accepts a single
index value and deserializes to a single index value.
This is because button_group can be single and multi select, but we use the same
proto for both and, thus, map single values to a list of values and a receiving
value wrapped in a list to a single value.
When a default_value is provided is provided, the option corresponding to the
index is serialized/deserialized.
"""
def __init__(
self,
option_indices: Sequence[T],
default_value: list[int] | None = None,
) -> None:
# see docstring about why we use MultiSelectSerde here
self.multiselect_serde: _MultiSelectSerde[T] = _MultiSelectSerde(
option_indices, default_value if default_value is not None else []
)
def serialize(self, value: T | None) -> list[int]:
_value = [value] if value is not None else []
return self.multiselect_serde.serialize(_value)
def deserialize(self, ui_value: list[int] | None) -> T | None:
deserialized = self.multiselect_serde.deserialize(ui_value)
if len(deserialized) == 0:
return None
return deserialized[0]
class ButtonGroupSerde(Generic[T]):
"""A serde that can handle both single and multi select options.
It uses the same proto to wire the data, so that we can send and receive
single values via a list. We have different serdes for both cases though so
that when setting / getting the value via session_state, it is mapped correctly.
So for single select, the value will be a single value and for multi select, it will
be a list of values.
"""
def __init__(
self,
options: Sequence[T],
default_values: list[int],
type: Literal["single", "multi"],
) -> None:
self.options = options
self.default_values = default_values
self.type = type
self.serde: _SingleSelectSerde[T] | _MultiSelectSerde[T] = (
_SingleSelectSerde(options, default_value=default_values)
if type == "single"
else _MultiSelectSerde(options, default_values)
)
def serialize(self, value: T | list[T] | None) -> list[int]:
return self.serde.serialize(cast("Any", value))
def deserialize(self, ui_value: list[int] | None) -> list[T] | T | None:
return self.serde.deserialize(ui_value)
def get_mapped_options(
feedback_option: Literal["thumbs", "faces", "stars"],
) -> tuple[list[ButtonGroupProto.Option], list[int]]:
# options object understandable by the web app
options: list[ButtonGroupProto.Option] = []
# we use the option index in the webapp communication to
# indicate which option is selected
options_indices: list[int] = []
if feedback_option == "thumbs":
# reversing the index mapping to have thumbs up first (but still with the higher
# index (=sentiment) in the list)
options_indices = list(reversed(range(len(_THUMB_ICONS))))
options = [ButtonGroupProto.Option(content_icon=icon) for icon in _THUMB_ICONS]
elif feedback_option == "faces":
options_indices = list(range(len(_FACES_ICONS)))
options = [ButtonGroupProto.Option(content_icon=icon) for icon in _FACES_ICONS]
elif feedback_option == "stars":
options_indices = list(range(_NUMBER_STARS))
options = [
ButtonGroupProto.Option(
content_icon=_STAR_ICON,
selected_content_icon=_SELECTED_STAR_ICON,
)
] * _NUMBER_STARS
return options, options_indices
def _build_proto(
widget_id: str,
formatted_options: Sequence[ButtonGroupProto.Option],
default_values: list[int],
disabled: bool,
current_form_id: str,
click_mode: ButtonGroupProto.ClickMode.ValueType,
selection_visualization: ButtonGroupProto.SelectionVisualization.ValueType = (
ButtonGroupProto.SelectionVisualization.ONLY_SELECTED
),
style: Literal["borderless", "pills", "segmented_control"] = "pills",
label: str | None = None,
label_visibility: LabelVisibility = "visible",
help: str | None = None,
) -> ButtonGroupProto:
proto = ButtonGroupProto()
proto.id = widget_id
proto.default[:] = default_values
proto.form_id = current_form_id
proto.disabled = disabled
proto.click_mode = click_mode
proto.style = ButtonGroupProto.Style.Value(style.upper())
# not passing the label looks the same as a collapsed label
if label is not None:
proto.label = label
proto.label_visibility.value = get_label_visibility_proto_value(
label_visibility
)
if help is not None:
proto.help = help
for formatted_option in formatted_options:
proto.options.append(formatted_option)
proto.selection_visualization = selection_visualization
return proto
def _maybe_raise_selection_mode_warning(selection_mode: SelectionMode) -> None:
"""Check if the selection_mode value is valid or raise exception otherwise."""
if selection_mode not in ["single", "multi"]:
raise StreamlitAPIException(
"The selection_mode argument must be one of ['single', 'multi']. "
f"The argument passed was '{selection_mode}'."
)
class ButtonGroupMixin:
# These overloads are not documented in the docstring, at least not at this time, on
# the theory that most people won't know what it means. And the Literals here are a
# subclass of int anyway. Usually, we would make a type alias for
# Literal["thumbs", "faces", "stars"]; but, in this case, we don't use it in too
# many other places, and it's a more helpful autocomplete if we just enumerate the
# values explicitly, so a decision has been made to keep it as not an alias.
@overload
def feedback(
self,
options: Literal["thumbs"] = ...,
*,
key: Key | None = None,
default: int | None = None,
disabled: bool = False,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
width: Width = "content",
) -> Literal[0, 1] | None: ...
@overload
def feedback(
self,
options: Literal["faces", "stars"] = ...,
*,
key: Key | None = None,
default: int | None = None,
disabled: bool = False,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
width: Width = "content",
) -> Literal[0, 1, 2, 3, 4] | None: ...
@gather_metrics("feedback")
def feedback(
self,
options: Literal["thumbs", "faces", "stars"] = "thumbs",
*,
key: Key | None = None,
default: int | None = None,
disabled: bool = False,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
width: Width = "content",
) -> int | None:
"""Display a feedback widget.
A feedback widget is an icon-based button group available in three
styles, as described in ``options``. It is commonly used in chat and AI
apps to allow users to rate responses.
Parameters
----------
options : "thumbs", "faces", or "stars"
The feedback options displayed to the user. ``options`` can be one
of the following:
- ``"thumbs"`` (default): Streamlit displays a thumb-up and
thumb-down button group.
- ``"faces"``: Streamlit displays a row of five buttons with
facial expressions depicting increasing satisfaction from left to
right.
- ``"stars"``: Streamlit displays a row of star icons, allowing the
user to select a rating from one to five stars.
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. No two widgets may have the same key.
default : int or None
Default feedback value. This must be consistent with the feedback
type in ``options``:
- 0 or 1 if ``options="thumbs"``.
- Between 0 and 4, inclusive, if ``options="faces"`` or
``options="stars"``.
disabled : bool
An optional boolean that disables the feedback widget if set
to ``True``. The default is ``False``.
on_change : callable
An optional callback invoked when this feedback widget's value
changes.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
width : "content", "stretch", or int
The width of the feedback widget. This can be one of the following:
- ``"content"`` (default): The width of the widget matches the
width of its content, but doesn't exceed the width of the parent
container.
- ``"stretch"``: The width of the widget matches the width of the
parent container.
- An integer specifying the width in pixels: The widget has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the widget matches the width
of the parent container.
Returns
-------
int or None
An integer indicating the user's selection, where ``0`` is the
lowest feedback. Higher values indicate more positive feedback.
If no option was selected, the widget returns ``None``.
- For ``options="thumbs"``, a return value of ``0`` indicates
thumbs-down, and ``1`` indicates thumbs-up.
- For ``options="faces"`` and ``options="stars"``, return values
range from ``0`` (least satisfied) to ``4`` (most satisfied).
Examples
--------
Display a feedback widget with stars, and show the selected sentiment:
>>> import streamlit as st
>>>
>>> sentiment_mapping = ["one", "two", "three", "four", "five"]
>>> selected = st.feedback("stars")
>>> if selected is not None:
>>> st.markdown(f"You selected {sentiment_mapping[selected]} star(s).")
.. output::
https://doc-feedback-stars.streamlit.app/
height: 200px
Display a feedback widget with thumbs, and show the selected sentiment:
>>> import streamlit as st
>>>
>>> sentiment_mapping = [":material/thumb_down:", ":material/thumb_up:"]
>>> selected = st.feedback("thumbs")
>>> if selected is not None:
>>> st.markdown(f"You selected: {sentiment_mapping[selected]}")
.. output::
https://doc-feedback-thumbs.streamlit.app/
height: 200px
"""
if options not in ["thumbs", "faces", "stars"]:
raise StreamlitAPIException(
"The options argument to st.feedback must be one of "
"['thumbs', 'faces', 'stars']. "
f"The argument passed was '{options}'."
)
transformed_options, options_indices = get_mapped_options(options)
if default is not None and (default < 0 or default >= len(transformed_options)):
raise StreamlitAPIException(
f"The default value in '{options}' must be a number between 0 and {len(transformed_options) - 1}."
f" The passed default value is {default}"
)
# Convert small pixel widths to "content" to prevent icon wrapping.
# Calculate threshold based on theme.baseFontSize to be responsive to
# custom themes. The calculation is based on icon buttons sized in rem:
# - Button size: ~1.5rem (icon 1.25rem + padding 0.125rem x 2)
# - Gap: 0.125rem between buttons
# - thumbs: 2 buttons + 1 gap = 3.125rem
# - faces/stars: 5 buttons + 4 gaps = 8rem
base_font_size = config.get_option("theme.baseFontSize") or 16
button_size_rem = 1.5
gap_size_rem = 0.125
if options == "thumbs":
# 2 buttons + 1 gap
min_width_rem = 2 * button_size_rem + gap_size_rem
else:
# 5 buttons + 4 gaps (faces or stars)
min_width_rem = 5 * button_size_rem + 4 * gap_size_rem
# Convert rem to pixels based on base font size, add 10% buffer
min_width_threshold = int(min_width_rem * base_font_size * 1.1)
if isinstance(width, int) and width < min_width_threshold:
width = "content"
_default: list[int] | None = (
[options_indices[default]] if default is not None else None
)
serde = _SingleSelectSerde[int](options_indices, default_value=_default)
selection_visualization = ButtonGroupProto.SelectionVisualization.ONLY_SELECTED
if options == "stars":
selection_visualization = (
ButtonGroupProto.SelectionVisualization.ALL_UP_TO_SELECTED
)
sentiment = self._button_group(
transformed_options,
default=_default,
key=key,
selection_mode="single",
disabled=disabled,
deserializer=serde.deserialize,
serializer=serde.serialize,
on_change=on_change,
args=args,
kwargs=kwargs,
selection_visualization=selection_visualization,
style="borderless",
width=width,
)
return sentiment.value
@overload
def pills(
self,
label: str,
options: OptionSequence[V],
*,
selection_mode: Literal["single"] = "single",
default: V | None = None,
format_func: Callable[[Any], str] | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: Width = "content",
) -> V | None: ...
@overload
def pills(
self,
label: str,
options: OptionSequence[V],
*,
selection_mode: Literal["multi"],
default: Sequence[V] | V | None = None,
format_func: Callable[[Any], str] | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: Width = "content",
) -> list[V]: ...
@gather_metrics("pills")
def pills(
self,
label: str,
options: OptionSequence[V],
*,
selection_mode: Literal["single", "multi"] = "single",
default: Sequence[V] | V | None = None,
format_func: Callable[[Any], str] | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: Width = "content",
) -> list[V] | V | None:
r"""Display a pills widget.
A pills widget is similar to a ``st.selectbox`` or ``st.multiselect``
where the ``options`` are displayed as pill-buttons instead of a
drop-down list.
Parameters
----------
label : str
A short label explaining to the user what this widget is for.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
For accessibility reasons, you should never set an empty label, but
you can hide it with ``label_visibility`` if needed. In the future,
we may disallow empty labels by raising an exception.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
options : Iterable of V
Labels for the select options in an ``Iterable``. This can be a
``list``, ``set``, or anything supported by ``st.dataframe``. If
``options`` is dataframe-like, the first column will be used. Each
label will be cast to ``str`` internally by default and can
optionally contain GitHub-flavored Markdown, including the Markdown
directives described in the ``body`` parameter of ``st.markdown``.
selection_mode : "single" or "multi"
The selection mode for the widget. If this is ``"single"``
(default), only one option can be selected. If this is ``"multi"``,
multiple options can be selected.
default : Iterable of V, V, or None
The value of the widget when it first renders. If the
``selection_mode`` is ``multi``, this can be a list of values, a
single value, or ``None``. If the ``selection_mode`` is
``"single"``, this can be a single value or ``None``.
format_func : function
Function to modify the display of the options. It receives
the raw option as an argument and should output the label to be
shown for that option. This has no impact on the return value of
the command. The output can optionally contain GitHub-flavored
Markdown, including the Markdown directives described in the
``body`` parameter of ``st.markdown``.
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. Multiple widgets of the same type may
not share the same key.
help : str or None
A tooltip that gets displayed next to the widget label. Streamlit
only displays the tooltip when ``label_visibility="visible"``. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
on_change : callable
An optional callback invoked when this widget's value changes.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
disabled : bool
An optional boolean that disables the widget if set to ``True``.
The default is ``False``.
label_visibility : "visible", "hidden", or "collapsed"
The visibility of the label. The default is ``"visible"``. If this
is ``"hidden"``, Streamlit displays an empty spacer instead of the
label, which can help keep the widget aligned with other widgets.
If this is ``"collapsed"``, Streamlit displays no label or spacer.
width : "content", "stretch", or int
The width of the pills widget. This can be one of the following:
- ``"content"`` (default): The width of the widget matches the
width of its content, but doesn't exceed the width of the parent
container.
- ``"stretch"``: The width of the widget matches the width of the
parent container.
- An integer specifying the width in pixels: The widget has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the widget matches the width
of the parent container.
Returns
-------
list of V, V, or None
If the ``selection_mode`` is ``multi``, this is a list of selected
options or an empty list. If the ``selection_mode`` is
``"single"``, this is a selected option or ``None``.
This contains copies of the selected options, not the originals.
Examples
--------
**Example 1: Multi-select pills**
Display a multi-select pills widget, and show the selection:
>>> import streamlit as st
>>>
>>> options = ["North", "East", "South", "West"]
>>> selection = st.pills("Directions", options, selection_mode="multi")
>>> st.markdown(f"Your selected options: {selection}.")
.. output::
https://doc-pills-multi.streamlit.app/
height: 200px
**Example 2: Single-select pills with icons**
Display a single-select pills widget with icons:
>>> import streamlit as st
>>>
>>> option_map = {
... 0: ":material/add:",
... 1: ":material/zoom_in:",
... 2: ":material/zoom_out:",
... 3: ":material/zoom_out_map:",
... }
>>> selection = st.pills(
... "Tool",
... options=option_map.keys(),
... format_func=lambda option: option_map[option],
... selection_mode="single",
... )
>>> st.write(
... "Your selected option: "
... f"{None if selection is None else option_map[selection]}"
... )
.. output::
https://doc-pills-single.streamlit.app/
height: 200px
"""
return self._internal_button_group(
options,
label=label,
selection_mode=selection_mode,
default=default,
format_func=format_func,
key=key,
help=help,
style="pills",
on_change=on_change,
args=args,
kwargs=kwargs,
disabled=disabled,
label_visibility=label_visibility,
width=width,
)
@overload
def segmented_control(
self,
label: str,
options: OptionSequence[V],
*,
selection_mode: Literal["single"] = "single",
default: V | None = None,
format_func: Callable[[Any], str] | None = None,
key: str | int | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: Width = "content",
) -> V | None: ...
@overload
def segmented_control(
self,
label: str,
options: OptionSequence[V],
*,
selection_mode: Literal["multi"],
default: Sequence[V] | V | None = None,
format_func: Callable[[Any], str] | None = None,
key: str | int | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: Width = "content",
) -> list[V]: ...
@gather_metrics("segmented_control")
def segmented_control(
self,
label: str,
options: OptionSequence[V],
*,
selection_mode: Literal["single", "multi"] = "single",
default: Sequence[V] | V | None = None,
format_func: Callable[[Any], str] | None = None,
key: str | int | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: Width = "content",
) -> list[V] | V | None:
r"""Display a segmented control widget.
A segmented control widget is a linear set of segments where each of
the passed ``options`` functions like a toggle button.
Parameters
----------
label : str
A short label explaining to the user what this widget is for.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
For accessibility reasons, you should never set an empty label, but
you can hide it with ``label_visibility`` if needed. In the future,
we may disallow empty labels by raising an exception.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
options : Iterable of V
Labels for the select options in an ``Iterable``. This can be a
``list``, ``set``, or anything supported by ``st.dataframe``. If
``options`` is dataframe-like, the first column will be used. Each
label will be cast to ``str`` internally by default and can
optionally contain GitHub-flavored Markdown, including the Markdown
directives described in the ``body`` parameter of ``st.markdown``.
selection_mode : "single" or "multi"
The selection mode for the widget. If this is ``"single"``
(default), only one option can be selected. If this is ``"multi"``,
multiple options can be selected.
default : Iterable of V, V, or None
The value of the widget when it first renders. If the
``selection_mode`` is ``multi``, this can be a list of values, a
single value, or ``None``. If the ``selection_mode`` is
``"single"``, this can be a single value or ``None``.
format_func : function
Function to modify the display of the options. It receives
the raw option as an argument and should output the label to be
shown for that option. This has no impact on the return value of
the command. The output can optionally contain GitHub-flavored
Markdown, including the Markdown directives described in the
``body`` parameter of ``st.markdown``.
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. Multiple widgets of the same type may
not share the same key.
help : str or None
A tooltip that gets displayed next to the widget label. Streamlit
only displays the tooltip when ``label_visibility="visible"``. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
on_change : callable
An optional callback invoked when this widget's value changes.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
disabled : bool
An optional boolean that disables the widget if set to ``True``.
The default is ``False``.
label_visibility : "visible", "hidden", or "collapsed"
The visibility of the label. The default is ``"visible"``. If this
is ``"hidden"``, Streamlit displays an empty spacer instead of the
label, which can help keep the widget aligned with other widgets.
If this is ``"collapsed"``, Streamlit displays no label or spacer.
width : "content", "stretch", or int
The width of the segmented control widget. This can be one of the
following:
- ``"content"`` (default): The width of the widget matches the
width of its content, but doesn't exceed the width of the parent
container.
- ``"stretch"``: The width of the widget matches the width of the
parent container.
- An integer specifying the width in pixels: The widget has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the widget matches the width
of the parent container.
Returns
-------
list of V, V, or None
If the ``selection_mode`` is ``multi``, this is a list of selected
options or an empty list. If the ``selection_mode`` is
``"single"``, this is a selected option or ``None``.
This contains copies of the selected options, not the originals.
Examples
--------
**Example 1: Multi-select segmented control**
Display a multi-select segmented control widget, and show the
selection:
>>> import streamlit as st
>>>
>>> options = ["North", "East", "South", "West"]
>>> selection = st.segmented_control(
... "Directions", options, selection_mode="multi"
... )
>>> st.markdown(f"Your selected options: {selection}.")
.. output::
https://doc-segmented-control-multi.streamlit.app/
height: 200px
**Example 2: Single-select segmented control with icons**
Display a single-select segmented control widget with icons:
>>> import streamlit as st
>>>
>>> option_map = {
... 0: ":material/add:",
... 1: ":material/zoom_in:",
... 2: ":material/zoom_out:",
... 3: ":material/zoom_out_map:",
... }
>>> selection = st.segmented_control(
... "Tool",
... options=option_map.keys(),
... format_func=lambda option: option_map[option],
... selection_mode="single",
... )
>>> st.write(
... "Your selected option: "
... f"{None if selection is None else option_map[selection]}"
... )
.. output::
https://doc-segmented-control-single.streamlit.app/
height: 200px
"""
return self._internal_button_group(
options,
label=label,
selection_mode=selection_mode,
default=default,
format_func=format_func,
key=key,
help=help,
style="segmented_control",
on_change=on_change,
args=args,
kwargs=kwargs,
disabled=disabled,
label_visibility=label_visibility,
width=width,
)
@gather_metrics("_internal_button_group")
def _internal_button_group(
self,
options: OptionSequence[V],
*,
key: Key | None = None,
default: Sequence[V] | V | None = None,
selection_mode: Literal["single", "multi"] = "single",
disabled: bool = False,
format_func: Callable[[Any], str] | None = None,
style: Literal["pills", "segmented_control"] = "segmented_control",
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
label: str | None = None,
label_visibility: LabelVisibility = "visible",
help: str | None = None,
width: Width = "content",
) -> list[V] | V | None:
maybe_raise_label_warnings(label, label_visibility)
def _transformed_format_func(option: V) -> ButtonGroupProto.Option:
"""If option starts with a material icon or an emoji, we extract it to send
it parsed to the frontend.
"""
transformed = format_func(option) if format_func else str(option)
transformed_parts = transformed.split(" ")
icon: str | None = None
if len(transformed_parts) > 0:
maybe_icon = transformed_parts[0].strip()
try:
if maybe_icon.startswith(":material"):
icon = validate_material_icon(maybe_icon)
elif is_emoji(maybe_icon):
icon = maybe_icon
if icon:
# reassamble the option string without the icon - also
# works if len(transformed_parts) == 1
transformed = " ".join(transformed_parts[1:])
except StreamlitAPIException:
# we don't have a valid icon or emoji, so we just pass
pass
return ButtonGroupProto.Option(
content=transformed,
content_icon=icon,
)
indexable_options = convert_to_sequence_and_check_comparable(options)
default_values = get_default_indices(indexable_options, default)
serde: ButtonGroupSerde[V] = ButtonGroupSerde[V](
indexable_options, default_values, selection_mode
)
res = self._button_group(
indexable_options,
default=default_values,
selection_mode=selection_mode,
disabled=disabled,
format_func=_transformed_format_func,
key=key,
help=help,
style=style,
serializer=serde.serialize,
deserializer=serde.deserialize,
on_change=on_change,
args=args,
kwargs=kwargs,
label=label,
label_visibility=label_visibility,
width=width,
)
if selection_mode == "multi":
return res.value
return res.value
def _button_group(
self,
indexable_options: Sequence[Any],
*,
key: Key | None = None,
default: list[int] | None = None,
selection_mode: SelectionMode = "single",
disabled: bool = False,
style: Literal[
"borderless", "pills", "segmented_control"
] = "segmented_control",
format_func: Callable[[V], ButtonGroupProto.Option] | None = None,
deserializer: WidgetDeserializer[T],
serializer: WidgetSerializer[T],
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
selection_visualization: ButtonGroupProto.SelectionVisualization.ValueType = (
ButtonGroupProto.SelectionVisualization.ONLY_SELECTED
),
label: str | None = None,
label_visibility: LabelVisibility = "visible",
help: str | None = None,
width: Width = "content",
) -> RegisterWidgetResult[T]:
_maybe_raise_selection_mode_warning(selection_mode)
parsed_selection_mode: ButtonGroupProto.ClickMode.ValueType = (
ButtonGroupProto.SINGLE_SELECT
if selection_mode == "single"
else ButtonGroupProto.MULTI_SELECT
)
# when selection mode is a single-value selection, the default must be a single
# value too.
if (
parsed_selection_mode == ButtonGroupProto.SINGLE_SELECT
and default is not None
and isinstance(default, Sequence)
and len(default) > 1
):
# add more commands to the error message
raise StreamlitAPIException(
"The default argument to `st.pills` must be a single value when "
"`selection_mode='single'`."
)
if style not in ["borderless", "pills", "segmented_control"]:
raise StreamlitAPIException(
"The style argument must be one of ['borderless', 'pills', 'segmented_control']. "
f"The argument passed was '{style}'."
)
key = to_key(key)
_default = default
if default is not None and len(default) == 0:
_default = None
validate_width(width, allow_content=True)
layout_config = LayoutConfig(width=width)
check_widget_policies(self.dg, key, on_change, default_value=_default)
ctx = get_script_run_ctx()
form_id = current_form_id(self.dg)
formatted_options = (
indexable_options
if format_func is None
else [
format_func(indexable_options[index])
for index, _ in enumerate(indexable_options)
]
)
element_id = compute_and_register_element_id(
# The borderless style is used by st.feedback, but users expect to see
# "feedback" in errors
"feedback" if style == "borderless" else style,
user_key=key,
# Treat the provided key as the main identity for segmented_control, pills and feedback,
# and only include kwargs that can invalidate the current selection.
# We whitelist the formatted options and the click mode (single vs multi).
key_as_main_identity={"options", "click_mode"},
dg=self.dg,
options=formatted_options,
default=default,
click_mode=parsed_selection_mode,
style=style,
width=width,
label=label,
help=help,
)
proto = _build_proto(
element_id,
formatted_options,
default or [],
disabled,
form_id,
click_mode=parsed_selection_mode,
selection_visualization=selection_visualization,
style=style,
label=label,
label_visibility=label_visibility,
help=help,
)
widget_state = register_widget(
proto.id,
on_change_handler=on_change,
args=args,
kwargs=kwargs,
deserializer=deserializer,
serializer=serializer,
ctx=ctx,
value_type="int_array_value",
)
if widget_state.value_changed:
proto.value[:] = serializer(widget_state.value)
proto.set_value = True
if ctx:
save_for_app_testing(ctx, element_id, format_func)
self.dg._enqueue("button_group", proto, layout_config=layout_config)
return widget_state
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/widgets/multiselect.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
from collections.abc import Sequence
from textwrap import dedent
from typing import (
TYPE_CHECKING,
Any,
Generic,
Literal,
TypeVar,
cast,
overload,
)
from streamlit.dataframe_util import OptionSequence, convert_anything_to_list
from streamlit.elements.lib.form_utils import current_form_id
from streamlit.elements.lib.layout_utils import (
LayoutConfig,
WidthWithoutContent,
validate_width,
)
from streamlit.elements.lib.options_selector_utils import (
convert_to_sequence_and_check_comparable,
create_mappings,
get_default_indices,
maybe_coerce_enum_sequence,
)
from streamlit.elements.lib.policies import (
check_widget_policies,
maybe_raise_label_warnings,
)
from streamlit.elements.lib.utils import (
Key,
LabelVisibility,
compute_and_register_element_id,
get_label_visibility_proto_value,
save_for_app_testing,
to_key,
)
from streamlit.errors import (
StreamlitSelectionCountExceedsMaxError,
)
from streamlit.proto.MultiSelect_pb2 import MultiSelect as MultiSelectProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner import ScriptRunContext, get_script_run_ctx
from streamlit.runtime.state import register_widget
from streamlit.type_util import (
is_iterable,
)
if TYPE_CHECKING:
from collections.abc import Callable, Sequence
from streamlit.dataframe_util import OptionSequence
from streamlit.delta_generator import DeltaGenerator
from streamlit.runtime.state import (
WidgetArgs,
WidgetCallback,
WidgetKwargs,
)
T = TypeVar("T")
class MultiSelectSerde(Generic[T]):
options: Sequence[T]
formatted_options: list[str]
formatted_option_to_option_index: dict[str, int]
default_options_indices: list[int]
def __init__(
self,
options: Sequence[T],
*,
formatted_options: list[str],
formatted_option_to_option_index: dict[str, int],
default_options_indices: list[int] | None = None,
) -> None:
"""Initialize the MultiSelectSerde.
We do not store an option_to_formatted_option mapping because the generic
options might not be hashable, which would raise a RuntimeError. So we do
two lookups: option -> index -> formatted_option[index].
Parameters
----------
options : Sequence[T]
The sequence of selectable options.
formatted_options : list[str]
The string representations of each option. The formatted_options correspond
to the options sequence by index.
formatted_option_to_option_index : dict[str, int]
A mapping from formatted option strings to their corresponding indices in
the options sequence.
default_option_index : int or None, optional
The index of the default option to use when no selection is made.
If None, no default option is selected.
"""
self.options = options
self.formatted_options = formatted_options
self.formatted_option_to_option_index = formatted_option_to_option_index
self.default_options_indices = default_options_indices or []
def serialize(self, value: list[T | str] | list[T]) -> list[str]:
converted_value = convert_anything_to_list(value)
values: list[str] = []
for v in converted_value:
try:
option_index = self.options.index(v)
values.append(self.formatted_options[option_index])
except ValueError: # noqa: PERF203
# at this point we know that v is a string, otherwise
# it would have been found in the options
values.append(cast("str", v))
return values
def deserialize(self, ui_value: list[str] | None) -> list[T | str] | list[T]:
if ui_value is None:
return [self.options[i] for i in self.default_options_indices]
values: list[T | str] = []
for v in ui_value:
try:
option_index = self.formatted_options.index(v)
values.append(self.options[option_index])
except ValueError: # noqa: PERF203
values.append(v)
return values
def _get_default_count(default: Sequence[Any] | Any | None) -> int:
if default is None:
return 0
if not is_iterable(default):
return 1
return len(cast("Sequence[Any]", default))
def _check_max_selections(
selections: Sequence[Any] | Any | None, max_selections: int | None
) -> None:
if max_selections is None:
return
default_count = _get_default_count(selections)
if default_count > max_selections:
raise StreamlitSelectionCountExceedsMaxError(
current_selections_count=default_count, max_selections_count=max_selections
)
class MultiSelectMixin:
@overload
def multiselect(
self,
label: str,
options: OptionSequence[T],
default: Any | None = None,
format_func: Callable[[Any], str] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
max_selections: int | None = None,
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
accept_new_options: Literal[False] = False,
width: WidthWithoutContent = "stretch",
) -> list[T]: ...
@overload
def multiselect(
self,
label: str,
options: OptionSequence[T],
default: Any | None = None,
format_func: Callable[[Any], str] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
max_selections: int | None = None,
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
accept_new_options: Literal[True] = True,
width: WidthWithoutContent = "stretch",
) -> list[T | str]: ...
@overload
def multiselect(
self,
label: str,
options: OptionSequence[T],
default: Any | None = None,
format_func: Callable[[Any], str] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
max_selections: int | None = None,
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
accept_new_options: bool = False,
width: WidthWithoutContent = "stretch",
) -> list[T] | list[T | str]: ...
@gather_metrics("multiselect")
def multiselect(
self,
label: str,
options: OptionSequence[T],
default: Any | None = None,
format_func: Callable[[Any], str] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
max_selections: int | None = None,
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
accept_new_options: Literal[False, True] | bool = False,
width: WidthWithoutContent = "stretch",
) -> list[T] | list[T | str]:
r"""Display a multiselect widget.
The multiselect widget starts as empty.
Parameters
----------
label : str
A short label explaining to the user what this select widget is for.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
For accessibility reasons, you should never set an empty label, but
you can hide it with ``label_visibility`` if needed. In the future,
we may disallow empty labels by raising an exception.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
options : Iterable
Labels for the select options in an ``Iterable``. This can be a
``list``, ``set``, or anything supported by ``st.dataframe``. If
``options`` is dataframe-like, the first column will be used. Each
label will be cast to ``str`` internally by default.
default : Iterable of V, V, or None
List of default values. Can also be a single value.
format_func : function
Function to modify the display of the options. It receives
the raw option as an argument and should output the label to be
shown for that option. This has no impact on the return value of
the command.
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. No two widgets may have the same key.
help : str or None
A tooltip that gets displayed next to the widget label. Streamlit
only displays the tooltip when ``label_visibility="visible"``. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
on_change : callable
An optional callback invoked when this widget's value changes.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
max_selections : int
The max selections that can be selected at a time.
placeholder : str or None
A string to display when no options are selected.
If this is ``None`` (default), the widget displays placeholder text
based on the widget's configuration:
- "Choose options" is displayed when options are available and
``accept_new_options=False``.
- "Choose or add options" is displayed when options are available
and ``accept_new_options=True``.
- "Add options" is displayed when no options are available and
``accept_new_options=True``.
- "No options to select" is displayed when no options are available
and ``accept_new_options=False``. The widget is also disabled in
this case.
disabled : bool
An optional boolean that disables the multiselect widget if set
to ``True``. The default is ``False``.
label_visibility : "visible", "hidden", or "collapsed"
The visibility of the label. The default is ``"visible"``. If this
is ``"hidden"``, Streamlit displays an empty spacer instead of the
label, which can help keep the widget aligned with other widgets.
If this is ``"collapsed"``, Streamlit displays no label or spacer.
accept_new_options : bool
Whether the user can add selections that aren't included in ``options``.
If this is ``False`` (default), the user can only select from the
items in ``options``. If this is ``True``, the user can enter new
items that don't exist in ``options``.
When a user enters and selects a new item, it is included in the
widget's returned list as a string. The new item is not added to
the widget's drop-down menu. Streamlit will use a case-insensitive
match from ``options`` before adding a new item, and a new item
can't be added if a case-insensitive match is already selected. The
``max_selections`` argument is still enforced.
width : "stretch" or int
The width of the multiselect widget. This can be one of the
following:
- ``"stretch"`` (default): The width of the widget matches the
width of the parent container.
- An integer specifying the width in pixels: The widget has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the widget matches the width
of the parent container.
Returns
-------
list
A list of the selected options.
The list contains copies of the selected options, not the originals.
Examples
--------
**Example 1: Use a basic multiselect widget**
You can declare one or more initial selections with the ``default``
parameter.
>>> import streamlit as st
>>>
>>> options = st.multiselect(
... "What are your favorite colors?",
... ["Green", "Yellow", "Red", "Blue"],
... default=["Yellow", "Red"],
... )
>>>
>>> st.write("You selected:", options)
.. output::
https://doc-multiselect.streamlit.app/
height: 350px
**Example 2: Let users to add new options**
To allow users to enter and select new options that aren't included in
the ``options`` list, use the ``accept_new_options`` parameter. To
prevent users from adding an unbounded number of new options, use the
``max_selections`` parameter.
>>> import streamlit as st
>>>
>>> options = st.multiselect(
... "What are your favorite cat names?",
... ["Jellybeans", "Fish Biscuit", "Madam President"],
... max_selections=5,
... accept_new_options=True,
... )
>>>
>>> st.write("You selected:", options)
.. output::
https://doc-multiselect-accept-new-options.streamlit.app/
height: 350px
"""
# Convert empty string to single space to distinguish from None:
# - None (default) → "" → Frontend shows contextual placeholders
# - "" (explicit empty) → " " → Frontend shows empty placeholder
# - "Custom" → "Custom" → Frontend shows custom placeholder
if placeholder == "":
placeholder = " "
ctx = get_script_run_ctx()
return self._multiselect(
label=label,
options=options,
default=default,
format_func=format_func,
key=key,
help=help,
on_change=on_change,
args=args,
kwargs=kwargs,
max_selections=max_selections,
placeholder=placeholder,
disabled=disabled,
label_visibility=label_visibility,
accept_new_options=accept_new_options,
width=width,
ctx=ctx,
)
def _multiselect(
self,
label: str,
options: OptionSequence[T],
default: Any | None = None,
format_func: Callable[[Any], str] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
max_selections: int | None = None,
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
accept_new_options: bool = False,
width: WidthWithoutContent = "stretch",
ctx: ScriptRunContext | None = None,
) -> list[T] | list[T | str]:
key = to_key(key)
widget_name = "multiselect"
check_widget_policies(
self.dg,
key,
on_change,
default_value=default,
)
maybe_raise_label_warnings(label, label_visibility)
indexable_options = convert_to_sequence_and_check_comparable(options)
formatted_options, formatted_option_to_option_index = create_mappings(
indexable_options, format_func
)
default_values = get_default_indices(indexable_options, default)
# Convert empty string to single space to distinguish from None:
# - None (default) → "" → Frontend shows contextual placeholders
# - "" (explicit empty) → " " → Frontend shows empty placeholder
# - "Custom" → "Custom" → Frontend shows custom placeholder
if placeholder == "":
placeholder = " "
form_id = current_form_id(self.dg)
element_id = compute_and_register_element_id(
widget_name,
user_key=key,
# Treat the provided key as the main identity. Only include
# changes to the options, accept_new_options, and max_selections
# in the identity computation as those can invalidate the
# current selection.
key_as_main_identity={
"options",
"max_selections",
"accept_new_options",
"format_func",
},
dg=self.dg,
label=label,
options=formatted_options,
default=default_values,
help=help,
max_selections=max_selections,
placeholder=placeholder,
accept_new_options=accept_new_options,
width=width,
)
proto = MultiSelectProto()
proto.id = element_id
proto.default[:] = default_values
proto.form_id = form_id
proto.disabled = disabled
proto.label = label
proto.max_selections = max_selections or 0
proto.placeholder = placeholder or ""
proto.label_visibility.value = get_label_visibility_proto_value(
label_visibility
)
proto.options[:] = formatted_options
if help is not None:
proto.help = dedent(help)
proto.accept_new_options = accept_new_options
serde = MultiSelectSerde(
indexable_options,
formatted_options=formatted_options,
formatted_option_to_option_index=formatted_option_to_option_index,
default_options_indices=default_values,
)
widget_state = register_widget(
proto.id,
on_change_handler=on_change,
args=args,
kwargs=kwargs,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="string_array_value",
)
_check_max_selections(widget_state.value, max_selections)
widget_state = maybe_coerce_enum_sequence(
widget_state, options, indexable_options
)
if widget_state.value_changed:
proto.raw_values[:] = serde.serialize(widget_state.value)
proto.set_value = True
validate_width(width)
layout_config = LayoutConfig(width=width)
if ctx:
save_for_app_testing(ctx, element_id, format_func)
self.dg._enqueue(widget_name, proto, layout_config=layout_config)
return widget_state.value
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/widgets/color_picker.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import re
from dataclasses import dataclass
from textwrap import dedent
from typing import TYPE_CHECKING, cast
from streamlit.elements.lib.form_utils import current_form_id
from streamlit.elements.lib.layout_utils import (
LayoutConfig,
Width,
validate_width,
)
from streamlit.elements.lib.policies import (
check_widget_policies,
maybe_raise_label_warnings,
)
from streamlit.elements.lib.utils import (
Key,
LabelVisibility,
compute_and_register_element_id,
get_label_visibility_proto_value,
to_key,
)
from streamlit.errors import StreamlitAPIException
from streamlit.proto.ColorPicker_pb2 import ColorPicker as ColorPickerProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner import ScriptRunContext, get_script_run_ctx
from streamlit.runtime.state import (
WidgetArgs,
WidgetCallback,
WidgetKwargs,
register_widget,
)
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
@dataclass
class ColorPickerSerde:
value: str
def serialize(self, v: str) -> str:
return str(v)
def deserialize(self, ui_value: str | None) -> str:
return str(ui_value if ui_value is not None else self.value)
class ColorPickerMixin:
@gather_metrics("color_picker")
def color_picker(
self,
label: str,
value: str | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: Width = "content",
) -> str:
r"""Display a color picker widget.
Parameters
----------
label : str
A short label explaining to the user what this input is for.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
For accessibility reasons, you should never set an empty label, but
you can hide it with ``label_visibility`` if needed. In the future,
we may disallow empty labels by raising an exception.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
value : str
The hex value of this widget when it first renders. If None,
defaults to black.
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. No two widgets may have the same key.
help : str or None
A tooltip that gets displayed next to the widget label. Streamlit
only displays the tooltip when ``label_visibility="visible"``. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
on_change : callable
An optional callback invoked when this color_picker's value
changes.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
disabled : bool
An optional boolean that disables the color picker if set to
``True``. The default is ``False``.
label_visibility : "visible", "hidden", or "collapsed"
The visibility of the label. The default is ``"visible"``. If this
is ``"hidden"``, Streamlit displays an empty spacer instead of the
label, which can help keep the widget aligned with other widgets.
If this is ``"collapsed"``, Streamlit displays no label or spacer.
width : "content", "stretch", or int
The width of the color picker widget. This can be one of the
following:
- ``"content"`` (default): The width of the widget matches the
width of its content, but doesn't exceed the width of the parent
container.
- ``"stretch"``: The width of the widget matches the width of the
parent container.
- An integer specifying the width in pixels: The widget has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the widget matches the width
of the parent container.
Returns
-------
str
The selected color as a hex string.
Example
-------
>>> import streamlit as st
>>>
>>> color = st.color_picker("Pick A Color", "#00f900")
>>> st.write("The current color is", color)
.. output::
https://doc-color-picker.streamlit.app/
height: 335px
"""
ctx = get_script_run_ctx()
return self._color_picker(
label=label,
value=value,
key=key,
help=help,
on_change=on_change,
args=args,
kwargs=kwargs,
disabled=disabled,
label_visibility=label_visibility,
width=width,
ctx=ctx,
)
def _color_picker(
self,
label: str,
value: str | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
width: Width = "content",
ctx: ScriptRunContext | None = None,
) -> str:
key = to_key(key)
check_widget_policies(
self.dg,
key,
on_change,
default_value=value,
)
maybe_raise_label_warnings(label, label_visibility)
# Enforce minimum width of 40px to match the color block's intrinsic size.
# The color block is always 40x40px, so the widget should never be smaller.
min_width_px = 40
if isinstance(width, int) and width < min_width_px:
width = min_width_px
validate_width(width, allow_content=True)
layout_config = LayoutConfig(width=width)
element_id = compute_and_register_element_id(
"color_picker",
user_key=key,
key_as_main_identity=True,
dg=self.dg,
label=label,
value=str(value),
help=help,
width=width,
)
# set value default
if value is None:
value = "#000000"
# make sure the value is a string
if not isinstance(value, str):
raise StreamlitAPIException(f"""
Color Picker Value has invalid type: {type(value).__name__}. Expects a hex string
like '#00FFAA' or '#000'.
""")
# validate the value and expects a hex string
match = re.match(r"^#(?:[0-9a-fA-F]{3}){1,2}$", value)
if not match:
raise StreamlitAPIException(f"""
'{value}' is not a valid hex code for colors. Valid ones are like
'#00FFAA' or '#000'.
""")
color_picker_proto = ColorPickerProto()
color_picker_proto.id = element_id
color_picker_proto.label = label
color_picker_proto.default = str(value)
color_picker_proto.form_id = current_form_id(self.dg)
color_picker_proto.disabled = disabled
color_picker_proto.label_visibility.value = get_label_visibility_proto_value(
label_visibility
)
if help is not None:
color_picker_proto.help = dedent(help)
serde = ColorPickerSerde(value)
widget_state = register_widget(
color_picker_proto.id,
on_change_handler=on_change,
args=args,
kwargs=kwargs,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="string_value",
)
if widget_state.value_changed:
color_picker_proto.value = widget_state.value
color_picker_proto.set_value = True
self.dg._enqueue(
"color_picker", color_picker_proto, layout_config=layout_config
)
return widget_state.value
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit/elements
|
hf_public_repos/streamlit/lib/streamlit/elements/widgets/number_input.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
from __future__ import annotations
import numbers
from dataclasses import dataclass
from textwrap import dedent
from typing import TYPE_CHECKING, Literal, TypeAlias, TypeVar, cast, overload
from streamlit.elements.lib.form_utils import current_form_id
from streamlit.elements.lib.js_number import JSNumber, JSNumberBoundsException
from streamlit.elements.lib.layout_utils import (
LayoutConfig,
WidthWithoutContent,
validate_width,
)
from streamlit.elements.lib.policies import (
check_widget_policies,
maybe_raise_label_warnings,
)
from streamlit.elements.lib.utils import (
Key,
LabelVisibility,
compute_and_register_element_id,
get_label_visibility_proto_value,
to_key,
)
from streamlit.errors import (
StreamlitInvalidNumberFormatError,
StreamlitJSNumberBoundsError,
StreamlitMixedNumericTypesError,
StreamlitValueAboveMaxError,
StreamlitValueBelowMinError,
)
from streamlit.proto.NumberInput_pb2 import NumberInput as NumberInputProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner import ScriptRunContext, get_script_run_ctx
from streamlit.runtime.state import (
WidgetArgs,
WidgetCallback,
WidgetKwargs,
get_session_state,
register_widget,
)
from streamlit.string_util import validate_icon_or_emoji
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
Number: TypeAlias = int | float
IntOrNone = TypeVar("IntOrNone", int, None)
FloatOrNone = TypeVar("FloatOrNone", float, None)
@dataclass
class NumberInputSerde:
value: Number | None
data_type: int
def serialize(self, v: Number | None) -> Number | None:
return v
def deserialize(self, ui_value: Number | None) -> Number | None:
val: Number | None = ui_value if ui_value is not None else self.value
if val is not None and self.data_type == NumberInputProto.INT:
val = int(val)
return val
class NumberInputMixin:
# If "min_value: int" is given and all other numerical inputs are
# "int"s or not provided (value optionally being "min"), return "int"
# If "min_value: int, value: None" is given and all other numerical inputs
# are "int"s or not provided, return "int | None"
@overload
def number_input(
self,
label: str,
min_value: int,
max_value: int | None = None,
value: IntOrNone | Literal["min"] = "min",
step: int | None = None,
format: str | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*,
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
icon: str | None = None,
width: WidthWithoutContent = "stretch",
) -> int | IntOrNone: ...
# If "max_value: int" is given and all other numerical inputs are
# "int"s or not provided (value optionally being "min"), return "int"
# If "max_value: int, value=None" is given and all other numerical inputs
# are "int"s or not provided, return "int | None"
@overload
def number_input(
self,
label: str,
min_value: None = None,
*,
max_value: int,
value: IntOrNone | Literal["min"] = "min",
step: int | None = None,
format: str | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
icon: str | None = None,
width: WidthWithoutContent = "stretch",
) -> int | IntOrNone: ...
# If "value=int" is given and all other numerical inputs are "int"s
# or not provided, return "int"
@overload
def number_input(
self,
label: str,
min_value: int | None = None,
max_value: int | None = None,
*,
value: int,
step: int | None = None,
format: str | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
icon: str | None = None,
width: WidthWithoutContent = "stretch",
) -> int: ...
# If "step=int" is given and all other numerical inputs are "int"s
# or not provided (value optionally being "min"), return "int"
# If "step=int, value=None" is given and all other numerical inputs
# are "int"s or not provided, return "int | None"
@overload
def number_input(
self,
label: str,
min_value: None = None,
max_value: None = None,
value: IntOrNone | Literal["min"] = "min",
*,
step: int,
format: str | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
icon: str | None = None,
width: WidthWithoutContent = "stretch",
) -> int | IntOrNone: ...
# If all numerical inputs are floats (with value optionally being "min")
# or are not provided, return "float"
# If only "value=None" is given and none of the other numerical inputs
# are "int"s, return "float | None"
@overload
def number_input(
self,
label: str,
min_value: float | None = None,
max_value: float | None = None,
value: FloatOrNone | Literal["min"] = "min",
step: float | None = None,
format: str | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*,
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
icon: str | None = None,
width: WidthWithoutContent = "stretch",
) -> float | FloatOrNone: ...
@gather_metrics("number_input")
def number_input(
self,
label: str,
min_value: Number | None = None,
max_value: Number | None = None,
value: Number | Literal["min"] | None = "min",
step: Number | None = None,
format: str | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
icon: str | None = None,
width: WidthWithoutContent = "stretch",
) -> Number | None:
r"""Display a numeric input widget.
.. note::
Integer values exceeding +/- ``(1<<53) - 1`` cannot be accurately
stored or returned by the widget due to serialization constraints
between the Python server and JavaScript client. You must handle
such numbers as floats, leading to a loss in precision.
Parameters
----------
label : str
A short label explaining to the user what this input is for.
The label can optionally contain GitHub-flavored Markdown of the
following types: Bold, Italics, Strikethroughs, Inline Code, Links,
and Images. Images display like icons, with a max height equal to
the font height.
Unsupported Markdown elements are unwrapped so only their children
(text contents) render. Display unsupported elements as literal
characters by backslash-escaping them. E.g.,
``"1\. Not an ordered list"``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
For accessibility reasons, you should never set an empty label, but
you can hide it with ``label_visibility`` if needed. In the future,
we may disallow empty labels by raising an exception.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
min_value : int, float, or None
The minimum permitted value.
If this is ``None`` (default), there will be no minimum for float
values and a minimum of ``- (1<<53) + 1`` for integer values.
max_value : int, float, or None
The maximum permitted value.
If this is ``None`` (default), there will be no maximum for float
values and a maximum of ``(1<<53) - 1`` for integer values.
value : int, float, "min" or None
The value of this widget when it first renders. If this is
``"min"`` (default), the initial value is ``min_value`` unless
``min_value`` is ``None``. If ``min_value`` is ``None``, the widget
initializes with a value of ``0.0`` or ``0``.
If ``value`` is ``None``, the widget will initialize with no value
and return ``None`` until the user provides input.
step : int, float, or None
The stepping interval.
Defaults to 1 if the value is an int, 0.01 otherwise.
If the value is not specified, the format parameter will be used.
format : str or None
A printf-style format string controlling how the interface should
display numbers. The output must be purely numeric. This does not
impact the return value of the widget. For more information about
the formatting specification, see `sprintf.js
<https://github.com/alexei/sprintf.js?tab=readme-ov-file#format-specification>`_.
For example, ``format="%0.1f"`` adjusts the displayed decimal
precision to only show one digit after the decimal.
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. No two widgets may have the same key.
help : str or None
A tooltip that gets displayed next to the widget label. Streamlit
only displays the tooltip when ``label_visibility="visible"``. If
this is ``None`` (default), no tooltip is displayed.
The tooltip can optionally contain GitHub-flavored Markdown,
including the Markdown directives described in the ``body``
parameter of ``st.markdown``.
on_change : callable
An optional callback invoked when this number_input's value changes.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
placeholder : str or None
An optional string displayed when the number input is empty.
If None, no placeholder is displayed.
disabled : bool
An optional boolean that disables the number input if set to
``True``. The default is ``False``.
label_visibility : "visible", "hidden", or "collapsed"
The visibility of the label. The default is ``"visible"``. If this
is ``"hidden"``, Streamlit displays an empty spacer instead of the
label, which can help keep the widget aligned with other widgets.
If this is ``"collapsed"``, Streamlit displays no label or spacer.
icon : str, None
An optional emoji or icon to display within the input field to the
left of the value. If ``icon`` is ``None`` (default), no icon is
displayed. If ``icon`` is a string, the following options are
valid:
- A single-character emoji. For example, you can set ``icon="🚨"``
or ``icon="🔥"``. Emoji short codes are not supported.
- An icon from the Material Symbols library (rounded style) in the
format ``":material/icon_name:"`` where "icon_name" is the name
of the icon in snake case.
For example, ``icon=":material/thumb_up:"`` will display the
Thumb Up icon. Find additional icons in the `Material Symbols \
<https://fonts.google.com/icons?icon.set=Material+Symbols&icon.style=Rounded>`_
font library.
- ``"spinner"``: Displays a spinner as an icon.
width : "stretch" or int
The width of the number input widget. This can be one of the
following:
- ``"stretch"`` (default): The width of the widget matches the
width of the parent container.
- An integer specifying the width in pixels: The widget has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the widget matches the width
of the parent container.
Returns
-------
int or float or None
The current value of the numeric input widget or ``None`` if the widget
is empty. The return type will match the data type of the value parameter.
Example
-------
>>> import streamlit as st
>>>
>>> number = st.number_input("Insert a number")
>>> st.write("The current number is ", number)
.. output::
https://doc-number-input.streamlit.app/
height: 260px
To initialize an empty number input, use ``None`` as the value:
>>> import streamlit as st
>>>
>>> number = st.number_input(
... "Insert a number", value=None, placeholder="Type a number..."
... )
>>> st.write("The current number is ", number)
.. output::
https://doc-number-input-empty.streamlit.app/
height: 260px
"""
ctx = get_script_run_ctx()
return self._number_input(
label=label,
min_value=min_value,
max_value=max_value,
value=value,
step=step,
format=format,
key=key,
help=help,
on_change=on_change,
args=args,
kwargs=kwargs,
placeholder=placeholder,
disabled=disabled,
label_visibility=label_visibility,
icon=icon,
width=width,
ctx=ctx,
)
def _number_input(
self,
label: str,
min_value: Number | None = None,
max_value: Number | None = None,
value: Number | Literal["min"] | None = "min",
step: Number | None = None,
format: str | None = None,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only arguments:
placeholder: str | None = None,
disabled: bool = False,
label_visibility: LabelVisibility = "visible",
icon: str | None = None,
width: WidthWithoutContent = "stretch",
ctx: ScriptRunContext | None = None,
) -> Number | None:
key = to_key(key)
check_widget_policies(
self.dg,
key,
on_change,
default_value=value if value != "min" else None,
)
maybe_raise_label_warnings(label, label_visibility)
element_id = compute_and_register_element_id(
"number_input",
user_key=key,
# Ensure stable ID when key is provided; explicitly whitelist parameters
# that might invalidate the current widget state.
key_as_main_identity={"min_value", "max_value", "step"},
dg=self.dg,
label=label,
min_value=min_value,
max_value=max_value,
value=value,
step=step,
format=format,
help=help,
placeholder=None if placeholder is None else str(placeholder),
icon=icon,
width=width,
)
# Ensure that all arguments are of the same type.
number_input_args = [min_value, max_value, value, step]
all_int_args = all(
isinstance(a, (numbers.Integral, type(None), str))
for a in number_input_args
)
all_float_args = all(
isinstance(a, (float, type(None), str)) for a in number_input_args
)
if not all_int_args and not all_float_args:
raise StreamlitMixedNumericTypesError(
value=value, min_value=min_value, max_value=max_value, step=step
)
session_state = get_session_state().filtered_state
if key is not None and key in session_state and session_state[key] is None:
value = None
if value == "min":
if min_value is not None:
value = min_value
elif all_int_args and all_float_args:
value = 0.0 # if no values are provided, defaults to float
elif all_int_args:
value = 0
else:
value = 0.0
int_value = isinstance(value, numbers.Integral)
float_value = isinstance(value, float)
if value is None:
if all_int_args and not all_float_args:
# Select int type if all relevant args are ints:
int_value = True
else:
# Otherwise, defaults to float:
float_value = True
# Use default format depending on value type if format was not provided:
number_format = ("%d" if int_value else "%0.2f") if format is None else format
# Warn user if they format an int type as a float or vice versa.
if number_format in ["%d", "%u", "%i"] and float_value:
import streamlit as st
st.warning(
"Warning: NumberInput value below has type float,"
f" but format {number_format} displays as integer."
)
elif number_format[-1] == "f" and int_value:
import streamlit as st
st.warning(
"Warning: NumberInput value below has type int so is"
f" displayed as int despite format string {number_format}."
)
if step is None:
step = 1 if int_value else 0.01
try:
float(number_format % 2)
except (TypeError, ValueError):
raise StreamlitInvalidNumberFormatError(number_format)
# Ensure that the value matches arguments' types.
all_ints = int_value and all_int_args
if min_value is not None and value is not None and min_value > value:
raise StreamlitValueBelowMinError(value=value, min_value=min_value)
if max_value is not None and value is not None and max_value < value:
raise StreamlitValueAboveMaxError(value=value, max_value=max_value)
# Bounds checks. JSNumber produces human-readable exceptions that
# we simply re-package as StreamlitAPIExceptions.
try:
if all_ints:
if min_value is not None:
JSNumber.validate_int_bounds(int(min_value), "`min_value`")
else:
# Issue 6740: If min_value not provided, set default to minimum safe integer
# to avoid JS issues from smaller numbers entered via UI
min_value = JSNumber.MIN_SAFE_INTEGER
if max_value is not None:
JSNumber.validate_int_bounds(int(max_value), "`max_value`")
else:
# See note above - set default to max safe integer
max_value = JSNumber.MAX_SAFE_INTEGER
if step is not None:
JSNumber.validate_int_bounds(int(step), "`step`")
if value is not None:
JSNumber.validate_int_bounds(int(value), "`value`")
else:
if min_value is not None:
JSNumber.validate_float_bounds(min_value, "`min_value`")
else:
# See note above
min_value = JSNumber.MIN_NEGATIVE_VALUE
if max_value is not None:
JSNumber.validate_float_bounds(max_value, "`max_value`")
else:
# See note above
max_value = JSNumber.MAX_VALUE
if step is not None:
JSNumber.validate_float_bounds(step, "`step`")
if value is not None:
JSNumber.validate_float_bounds(value, "`value`")
except JSNumberBoundsException as e:
raise StreamlitJSNumberBoundsError(str(e))
data_type = NumberInputProto.INT if all_ints else NumberInputProto.FLOAT
number_input_proto = NumberInputProto()
number_input_proto.id = element_id
number_input_proto.data_type = data_type
number_input_proto.label = label
if value is not None:
number_input_proto.default = value
if placeholder is not None:
number_input_proto.placeholder = str(placeholder)
number_input_proto.form_id = current_form_id(self.dg)
number_input_proto.disabled = disabled
number_input_proto.label_visibility.value = get_label_visibility_proto_value(
label_visibility
)
if help is not None:
number_input_proto.help = dedent(help)
if min_value is not None:
number_input_proto.min = min_value
number_input_proto.has_min = True
if max_value is not None:
number_input_proto.max = max_value
number_input_proto.has_max = True
if step is not None:
number_input_proto.step = step
number_input_proto.format = number_format
if icon is not None:
number_input_proto.icon = validate_icon_or_emoji(icon)
serde = NumberInputSerde(value, data_type)
widget_state = register_widget(
number_input_proto.id,
on_change_handler=on_change,
args=args,
kwargs=kwargs,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="double_value",
)
if widget_state.value_changed:
if widget_state.value is not None:
# Min/Max bounds checks when the value is updated.
if (
number_input_proto.has_min
and widget_state.value < number_input_proto.min
):
raise StreamlitValueBelowMinError(
value=widget_state.value, min_value=number_input_proto.min
)
if (
number_input_proto.has_max
and widget_state.value > number_input_proto.max
):
raise StreamlitValueAboveMaxError(
value=widget_state.value, max_value=number_input_proto.max
)
number_input_proto.value = widget_state.value
number_input_proto.set_value = True
validate_width(width)
layout_config = LayoutConfig(width=width)
self.dg._enqueue(
"number_input", number_input_proto, layout_config=layout_config
)
return widget_state.value
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
|
0
|
hf_public_repos/streamlit/lib/streamlit
|
hf_public_repos/streamlit/lib/streamlit/proto/__init__.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
# (This comment is here so the file exists in Git)
|
0
|
hf_public_repos/streamlit
|
hf_public_repos/streamlit/frontend/.prettierrc
|
{
"semi": false,
"trailingComma": "es5",
"arrowParens": "avoid"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.