streambricks 0.2.15__tar.gz → 0.2.17__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. {streambricks-0.2.15 → streambricks-0.2.17}/.gitignore +1 -0
  2. {streambricks-0.2.15 → streambricks-0.2.17}/PKG-INFO +1 -1
  3. {streambricks-0.2.15 → streambricks-0.2.17}/src/streambricks/__init__.py +19 -1
  4. streambricks-0.2.17/src/streambricks/auth/__init__.py +14 -0
  5. streambricks-0.2.17/src/streambricks/auth/decorator.py +78 -0
  6. streambricks-0.2.17/src/streambricks/auth/helpers.py +122 -0
  7. streambricks-0.2.17/src/streambricks/auth/models.py +105 -0
  8. streambricks-0.2.17/src/streambricks/helpers.py +149 -0
  9. streambricks-0.2.17/src/streambricks/widgets/image_capture.py +45 -0
  10. {streambricks-0.2.15 → streambricks-0.2.17}/src/streambricks/widgets/model_widget/main.py +17 -63
  11. streambricks-0.2.17/src/streambricks/widgets/sequence.py +112 -0
  12. streambricks-0.2.15/src/streambricks/helpers.py +0 -48
  13. {streambricks-0.2.15 → streambricks-0.2.17}/.copier-answers.yml +0 -0
  14. {streambricks-0.2.15 → streambricks-0.2.17}/.github/FUNDING.yml +0 -0
  15. {streambricks-0.2.15 → streambricks-0.2.17}/.github/copilot-instructions.md +0 -0
  16. {streambricks-0.2.15 → streambricks-0.2.17}/.github/dependabot.yml +0 -0
  17. {streambricks-0.2.15 → streambricks-0.2.17}/.github/workflows/build.yml +0 -0
  18. {streambricks-0.2.15 → streambricks-0.2.17}/.github/workflows/documentation.yml +0 -0
  19. {streambricks-0.2.15 → streambricks-0.2.17}/.pre-commit-config.yaml +0 -0
  20. {streambricks-0.2.15 → streambricks-0.2.17}/LICENSE +0 -0
  21. {streambricks-0.2.15 → streambricks-0.2.17}/README.md +0 -0
  22. {streambricks-0.2.15 → streambricks-0.2.17}/docs/.empty +0 -0
  23. {streambricks-0.2.15 → streambricks-0.2.17}/duties.py +0 -0
  24. {streambricks-0.2.15 → streambricks-0.2.17}/mkdocs.yml +0 -0
  25. {streambricks-0.2.15 → streambricks-0.2.17}/overrides/_dummy.txt +0 -0
  26. {streambricks-0.2.15 → streambricks-0.2.17}/pyproject.toml +0 -0
  27. {streambricks-0.2.15 → streambricks-0.2.17}/src/streambricks/py.typed +0 -0
  28. {streambricks-0.2.15 → streambricks-0.2.17}/src/streambricks/state.py +0 -0
  29. {streambricks-0.2.15 → streambricks-0.2.17}/src/streambricks/widgets/__init__.py +0 -0
  30. {streambricks-0.2.15 → streambricks-0.2.17}/src/streambricks/widgets/bind_kwargs.py +0 -0
  31. {streambricks-0.2.15 → streambricks-0.2.17}/src/streambricks/widgets/model_selector.py +0 -0
  32. {streambricks-0.2.15 → streambricks-0.2.17}/src/streambricks/widgets/model_widget/__init__.py +0 -0
  33. {streambricks-0.2.15 → streambricks-0.2.17}/src/streambricks/widgets/model_widget/field_metadata_renderers.py +0 -0
  34. {streambricks-0.2.15 → streambricks-0.2.17}/src/streambricks/widgets/model_widget/type_renderers.py +0 -0
  35. {streambricks-0.2.15 → streambricks-0.2.17}/src/streambricks/widgets/multi_select.py +0 -0
  36. {streambricks-0.2.15 → streambricks-0.2.17}/src/streambricks/widgets/type_helpers.py +0 -0
  37. {streambricks-0.2.15 → streambricks-0.2.17}/tests/__init__.py +0 -0
  38. {streambricks-0.2.15 → streambricks-0.2.17}/tests/conftest.py +0 -0
  39. {streambricks-0.2.15 → streambricks-0.2.17}/tests/test_widgets.py +0 -0
@@ -30,3 +30,4 @@ junit.xml
30
30
  uv.lock
31
31
  # DiskCache cache file
32
32
  ./model_cache
33
+ .streamlit/secrets.toml
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: streambricks
3
- Version: 0.2.15
3
+ Version: 0.2.17
4
4
  Summary: Streamlit widgets and helpers
5
5
  Project-URL: Documentation, https://phil65.github.io/streambricks/
6
6
  Project-URL: Source, https://github.com/phil65/streambricks
@@ -1,11 +1,22 @@
1
- __version__ = "0.2.15"
1
+ """StreamBricks components for Streamlit."""
2
2
 
3
+ __version__ = "0.2.17"
3
4
 
5
+
6
+ from streambricks.auth import (
7
+ GoogleUser,
8
+ MicrosoftUser,
9
+ get_current_user,
10
+ google_login,
11
+ microsoft_login,
12
+ requires_login,
13
+ )
4
14
  from streambricks.widgets.model_widget import (
5
15
  render_model_form as model_edit,
6
16
  render_model_readonly as model_display,
7
17
  )
8
18
  from streambricks.widgets.multi_select import multiselect, MultiSelectItem
19
+ from streambricks.widgets.image_capture import image_capture
9
20
  from streambricks.widgets.model_selector import (
10
21
  model_selector,
11
22
  model_selector as llm_model_selector,
@@ -15,13 +26,20 @@ from streambricks.state import State
15
26
  from streambricks.widgets.bind_kwargs import bind_kwargs_as_widget
16
27
 
17
28
  __all__ = [
29
+ "GoogleUser",
30
+ "MicrosoftUser",
18
31
  "MultiSelectItem",
19
32
  "State",
20
33
  "bind_kwargs_as_widget",
34
+ "get_current_user",
35
+ "google_login",
36
+ "image_capture",
21
37
  "llm_model_selector",
38
+ "microsoft_login",
22
39
  "model_display",
23
40
  "model_edit",
24
41
  "model_selector",
25
42
  "multiselect",
43
+ "requires_login",
26
44
  "run",
27
45
  ]
@@ -0,0 +1,14 @@
1
+ from __future__ import annotations
2
+
3
+ from streambricks.auth.decorator import requires_login
4
+ from streambricks.auth.helpers import get_current_user, google_login, microsoft_login
5
+ from streambricks.auth.models import GoogleUser, MicrosoftUser
6
+
7
+ __all__ = [
8
+ "GoogleUser",
9
+ "MicrosoftUser",
10
+ "get_current_user",
11
+ "google_login",
12
+ "microsoft_login",
13
+ "requires_login",
14
+ ]
@@ -0,0 +1,78 @@
1
+ from __future__ import annotations
2
+
3
+ import functools
4
+ from typing import TYPE_CHECKING, Any, ParamSpec, TypeVar
5
+
6
+ import streamlit as st
7
+
8
+
9
+ if TYPE_CHECKING:
10
+ from collections.abc import Callable
11
+
12
+
13
+ T = TypeVar("T")
14
+ P = ParamSpec("P")
15
+
16
+
17
+ def requires_login(
18
+ func: Callable[P, T] | None = None,
19
+ *,
20
+ unauthorized_handler: str | Callable[[], Any] | None = None,
21
+ ) -> Callable[P, T] | Callable[[Callable[P, T]], Callable[P, T]]:
22
+ """Decorator that requires a user to be logged in via Streamlit.
23
+
24
+ Args:
25
+ func: The function to wrap. If None, returns a decorator.
26
+ unauthorized_handler: How to handle unauthorized access:
27
+ - If None: Shows default error message
28
+ - If str: Shows that string as an error message
29
+ - If Callable: Calls the function for custom handling
30
+
31
+ Returns:
32
+ Decorated function that checks login status before executing.
33
+
34
+ Examples:
35
+ @requires_login
36
+ def protected_page():
37
+ st.write("Protected content")
38
+
39
+ @requires_login(unauthorized_handler="Please log in first")
40
+ def dashboard():
41
+ st.write("Dashboard content")
42
+
43
+ @requires_login(unauthorized_handler=lambda: st.switch_page("pages/login.py"))
44
+ def analytics():
45
+ st.write("Analytics")
46
+ """
47
+
48
+ def default_unauthorized_handler() -> None:
49
+ st.error("You need to be logged in to access this page")
50
+ st.button("Log in with Google", on_click=st.login)
51
+
52
+ def get_handler() -> Callable[[], Any]:
53
+ if unauthorized_handler is None:
54
+ return default_unauthorized_handler
55
+ if isinstance(unauthorized_handler, str):
56
+ return lambda: st.error(unauthorized_handler)
57
+ return unauthorized_handler
58
+
59
+ def decorator(fn: Callable[P, T]) -> Callable[P, T]:
60
+ @functools.wraps(fn)
61
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
62
+ if hasattr(st, "experimental_user") and st.experimental_user.is_logged_in:
63
+ return fn(*args, **kwargs)
64
+
65
+ # Handle unauthorized access
66
+ handler = get_handler()
67
+ handler()
68
+
69
+ # Return early with None
70
+ return None # type: ignore
71
+
72
+ return wrapper
73
+
74
+ # Handle both @requires_login and @requires_login()
75
+ if func is None:
76
+ return decorator
77
+
78
+ return decorator(func)
@@ -0,0 +1,122 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, TypeVar, overload
4
+
5
+ import streamlit as st
6
+
7
+ from streambricks.auth.models import GoogleUser, MicrosoftUser
8
+
9
+
10
+ T = TypeVar("T", GoogleUser, MicrosoftUser)
11
+
12
+
13
+ def _get_user_data() -> dict[str, Any] | None:
14
+ """Get user data from either experimental_user or stable user attribute."""
15
+ # Try stable version first
16
+ if hasattr(st, "user") and getattr(st.user, "is_logged_in", False): # pyright: ignore
17
+ return {**st.user} # pyright: ignore
18
+
19
+ # Fall back to experimental version
20
+ if hasattr(st, "experimental_user") and st.experimental_user.is_logged_in:
21
+ return {**st.experimental_user}
22
+
23
+ return None
24
+
25
+
26
+ def google_login(
27
+ button_text: str = "Login with Google",
28
+ redirect_url: str | None = None,
29
+ key: str | None = None,
30
+ ) -> GoogleUser | None:
31
+ """Authenticate user with Google and return typed user object if successful.
32
+
33
+ Args:
34
+ button_text: Text to display on the login button
35
+ redirect_url: URL to redirect to after successful login
36
+ key: Streamlit widget key for the login button
37
+
38
+ Returns:
39
+ GoogleUser object if login successful, None otherwise
40
+ """
41
+ user_data = _get_user_data()
42
+ if user_data is not None:
43
+ # User is already logged in, return typed user object
44
+ return GoogleUser(is_logged_in=True, **user_data) # pyright: ignore
45
+
46
+ # User not logged in, display login button
47
+ if st.button(button_text, key=key):
48
+ # The provider parameter should match what's configured in secrets.toml
49
+ st.login("google")
50
+
51
+ return None
52
+
53
+
54
+ def microsoft_login(
55
+ button_text: str = "Login with Microsoft",
56
+ redirect_url: str | None = None,
57
+ key: str | None = None,
58
+ ) -> MicrosoftUser | None:
59
+ """Authenticate user with Microsoft and return typed user object if successful.
60
+
61
+ Args:
62
+ button_text: Text to display on the login button
63
+ redirect_url: URL to redirect to after successful login
64
+ key: Streamlit widget key for the login button
65
+
66
+ Returns:
67
+ MicrosoftUser object if login successful, None otherwise
68
+ """
69
+ user_data = _get_user_data()
70
+ if user_data is not None:
71
+ # User is already logged in, return typed user object
72
+ return MicrosoftUser(is_logged_in=True, **user_data) # pyright: ignore
73
+
74
+ # User not logged in, display login button
75
+ if st.button(button_text, key=key):
76
+ # The provider parameter should match what's configured in secrets.toml
77
+ st.login("microsoft")
78
+
79
+ return None
80
+
81
+
82
+ @overload
83
+ def get_current_user(user_class: type[T]) -> T: ...
84
+
85
+
86
+ @overload
87
+ def get_current_user() -> GoogleUser | MicrosoftUser | None: ...
88
+
89
+
90
+ def get_current_user(
91
+ user_class: type[T] | None = None,
92
+ ) -> T | GoogleUser | MicrosoftUser | None:
93
+ """Get the currently logged in user as a typed object.
94
+
95
+ Args:
96
+ user_class: The class to use for the user model (GoogleUser or MicrosoftUser).
97
+ If specified, errors will be raised if the data doesn't match.
98
+
99
+ Returns:
100
+ Typed user object if logged in and matching requested type,
101
+ None if no user_class specified and no user is logged in
102
+
103
+ Raises:
104
+ Various exceptions: If the user data doesn't match the requested model,
105
+ the original validation exceptions from Pydantic will be raised
106
+ """
107
+ user_data = _get_user_data()
108
+ if user_data is None:
109
+ if user_class is not None:
110
+ msg = "No user is currently logged in"
111
+ raise ValueError(msg)
112
+ return None
113
+
114
+ if user_class is not None:
115
+ return user_class(is_logged_in=True, **user_data) # pyright: ignore
116
+ try:
117
+ return GoogleUser(is_logged_in=True, **user_data) # pyright: ignore
118
+ except Exception: # noqa: BLE001
119
+ try:
120
+ return MicrosoftUser(is_logged_in=True, **user_data) # pyright: ignore
121
+ except Exception: # noqa: BLE001
122
+ return None
@@ -0,0 +1,105 @@
1
+ from __future__ import annotations
2
+
3
+ from pydantic import BaseModel, ConfigDict, Field
4
+
5
+
6
+ class MicrosoftUser(BaseModel):
7
+ """Microsoft Identity Token information from Streamlit's experimental_user."""
8
+
9
+ model_config = ConfigDict(use_attribute_docstrings=True)
10
+
11
+ is_logged_in: bool
12
+ """Whether the user is currently logged in"""
13
+
14
+ ver: str
15
+ """Version of the token format"""
16
+
17
+ iss: str
18
+ """The service that issued the token"""
19
+
20
+ sub: str
21
+ """Subject identifier for the user"""
22
+
23
+ application_id: str = Field(alias="aud")
24
+ """Intended recipient of the token (your application)"""
25
+
26
+ expiration_time: int = Field(alias="exp")
27
+ """Timestamp when the token expires"""
28
+
29
+ issued_time: int = Field(alias="iat")
30
+ """Timestamp when the token was issued"""
31
+
32
+ start_time: int = Field(alias="nbf")
33
+ """Timestamp when the token becomes valid"""
34
+
35
+ name: str
36
+ """Complete name of the user"""
37
+
38
+ username: str = Field(alias="preferred_username")
39
+ """Preferred username for the user account"""
40
+
41
+ user_id: str = Field(alias="oid")
42
+ """Unique Microsoft identifier for the user"""
43
+
44
+ email: str
45
+ """Email address of the authenticated user"""
46
+
47
+ tenant_id: str = Field(alias="tid")
48
+ """Microsoft Entra tenant identifier"""
49
+
50
+ nonce: str
51
+ """One-time value to prevent replay attacks"""
52
+
53
+ aio: str
54
+ """Internal Microsoft authentication tracking information"""
55
+
56
+
57
+ class GoogleUser(BaseModel):
58
+ """Google Identity Token information from Streamlit's experimental_user."""
59
+
60
+ model_config = ConfigDict(use_attribute_docstrings=True, extra="allow")
61
+
62
+ is_logged_in: bool
63
+ """Authentication status of the user"""
64
+
65
+ iss: str
66
+ """The service that issued the token"""
67
+
68
+ authorized_party: str = Field(alias="azp")
69
+ """The client that was authorized to receive the token"""
70
+
71
+ client_id: str = Field(alias="aud")
72
+ """Intended recipient of the token (your application)"""
73
+
74
+ user_id: str = Field(alias="sub")
75
+ """Unique Google identifier for the user"""
76
+
77
+ email: str
78
+ """Email address of the authenticated user"""
79
+
80
+ email_verified: bool
81
+ """Confirmation that Google has verified the email address"""
82
+
83
+ access_token_hash: str = Field(alias="at_hash")
84
+ """Hash of access token for security validation"""
85
+
86
+ nonce: str
87
+ """One-time value to prevent replay attacks"""
88
+
89
+ name: str
90
+ """Complete name of the user"""
91
+
92
+ picture: str
93
+ """Link to the user's Google profile image"""
94
+
95
+ given_name: str
96
+ """First/given name of the user"""
97
+
98
+ family_name: str
99
+ """Last/family name of the user"""
100
+
101
+ issued_time: int = Field(alias="iat")
102
+ """Timestamp when the token was issued"""
103
+
104
+ expiration_time: int = Field(alias="exp")
105
+ """Timestamp when the token expires"""
@@ -0,0 +1,149 @@
1
+ """Utility functions for Streamlit applications."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from datetime import date, datetime, time
7
+ from decimal import Decimal
8
+ from enum import Enum
9
+ import inspect
10
+ import sys
11
+ from typing import TYPE_CHECKING, Any, get_args
12
+
13
+ import streamlit as st
14
+ from streamlit import runtime
15
+ from streamlit.web.cli import main
16
+
17
+ from streambricks.widgets.type_helpers import is_literal_type
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from collections.abc import Callable, Coroutine
22
+
23
+ from streamlit.elements.lib.column_types import ColumnConfig
24
+
25
+
26
+ def run(fn: Callable[..., Any] | Coroutine[Any, Any, Any], *args: Any, **kwargs: Any):
27
+ """Run a function or coroutine with Streamlit.
28
+
29
+ If Streamlit runtime exists, execute the function directly. Otherwise,
30
+ start Streamlit with the current script.
31
+
32
+ Args:
33
+ fn: The function or coroutine to run
34
+ args: Positional arguments to pass to the function
35
+ kwargs: Keyword arguments to pass to the function
36
+ """
37
+ if runtime.exists():
38
+ if inspect.iscoroutine(fn):
39
+ asyncio.run(fn)
40
+ # Handle coroutine function
41
+ elif inspect.iscoroutinefunction(fn):
42
+ coro = fn(*args, **kwargs)
43
+ asyncio.run(coro)
44
+ # Handle regular function
45
+ else:
46
+ fn(*args, **kwargs) # type: ignore
47
+ else:
48
+ sys.argv = ["streamlit", "run", sys.argv[0]]
49
+ sys.exit(main())
50
+
51
+
52
+ def get_column_for_type( # noqa: PLR0911
53
+ typ: type,
54
+ title: str,
55
+ *,
56
+ required: bool = True,
57
+ help: str | None = None, # noqa: A002
58
+ **kwargs: Any,
59
+ ) -> ColumnConfig:
60
+ """Get appropriate column config for a given type.
61
+
62
+ Args:
63
+ typ: The type to create a column for
64
+ title: Column title/label
65
+ required: Whether the field is required
66
+ help: Help text for the column
67
+ **kwargs: Additional arguments passed to column constructor
68
+
69
+ Returns:
70
+ Configured column for the type
71
+ """
72
+ # Handle literal types
73
+ if is_literal_type(typ):
74
+ options = get_args(typ)
75
+ return st.column_config.SelectboxColumn(
76
+ title,
77
+ help=help,
78
+ required=required,
79
+ options=options,
80
+ **kwargs,
81
+ )
82
+
83
+ # Handle enums
84
+ if isinstance(typ, type) and issubclass(typ, Enum):
85
+ return st.column_config.SelectboxColumn(
86
+ title,
87
+ help=help,
88
+ required=required,
89
+ options=list(typ.__members__.values()), # type: ignore
90
+ **kwargs,
91
+ )
92
+
93
+ # Match on type
94
+ match typ:
95
+ case type() as t if t is bool:
96
+ return st.column_config.CheckboxColumn(
97
+ title,
98
+ help=help,
99
+ **kwargs,
100
+ )
101
+
102
+ case type() as t if t in (int, float, Decimal):
103
+ return st.column_config.NumberColumn(
104
+ title,
105
+ help=help,
106
+ required=required,
107
+ **kwargs,
108
+ )
109
+
110
+ case type() as t if t is str:
111
+ return st.column_config.TextColumn(
112
+ title,
113
+ help=help,
114
+ required=required,
115
+ **kwargs,
116
+ )
117
+
118
+ case type() as t if t is datetime:
119
+ return st.column_config.DatetimeColumn(
120
+ title,
121
+ help=help,
122
+ required=required,
123
+ **kwargs,
124
+ )
125
+
126
+ case type() as t if t is date:
127
+ return st.column_config.DateColumn(
128
+ title,
129
+ help=help,
130
+ required=required,
131
+ **kwargs,
132
+ )
133
+
134
+ case type() as t if t is time:
135
+ return st.column_config.TimeColumn(
136
+ title,
137
+ help=help,
138
+ required=required,
139
+ **kwargs,
140
+ )
141
+
142
+ case _:
143
+ # Default to generic column for unsupported types
144
+ return st.column_config.Column(
145
+ title,
146
+ help=help,
147
+ required=required,
148
+ **kwargs,
149
+ )
@@ -0,0 +1,45 @@
1
+ """Model selector component for streamlit applications."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ import streamlit as st
8
+
9
+
10
+ if TYPE_CHECKING:
11
+ from streamlit.runtime.uploaded_file_manager import UploadedFile
12
+
13
+
14
+ def image_capture(
15
+ *,
16
+ image_label: str | None = None,
17
+ camera_label: str | None = None,
18
+ supported_types: list[str] | None = None,
19
+ ) -> UploadedFile | None:
20
+ """Capture an image from a file upload or camera.
21
+
22
+ Args:
23
+ image_label: Label for the file upload widget.
24
+ camera_label: Label for the camera input widget.
25
+ supported_types: List of supported file types for image upload.
26
+
27
+ Returns:
28
+ Uploaded file or None if not selected.
29
+ """
30
+ tab1, tab2 = st.tabs(["Upload file", "Use camera"])
31
+ with tab1:
32
+ types_ = supported_types or ["pdf", "png", "jpg", "jpeg"]
33
+ supported_str = f"Supported file types: {', '.join(types_)}"
34
+ uploaded_file = st.file_uploader(
35
+ image_label or "Upload picture", type=types_, help=supported_str
36
+ )
37
+ with tab2:
38
+ camera_file = st.camera_input(
39
+ camera_label or "Use camera to capture image",
40
+ )
41
+ if uploaded_file is not None:
42
+ return uploaded_file
43
+ if camera_file is not None:
44
+ return camera_file
45
+ return None
@@ -293,73 +293,27 @@ def render_sequence_field(
293
293
  disabled: bool = False,
294
294
  help: str | None = None, # noqa: A002
295
295
  **field_info: Any,
296
- ) -> list[Any]:
296
+ ) -> list[Any] | tuple[Any, ...]:
297
297
  """Render a field for sequence types (list, tuple, set)."""
298
- add_item_key = f"{key}_add_item"
299
- items_key = f"{key}_items"
300
- if items_key not in st.session_state:
301
- st.session_state[items_key] = list(value) if value is not None else []
302
- item_type = get_inner_type(field_info)
303
- st.markdown(f"**{label or key}**")
304
- if help:
305
- st.caption(help)
306
-
307
- with st.container():
308
- if st.button("Add Item", key=add_item_key, disabled=disabled):
309
- add_new_item(st.session_state[items_key], item_type)
310
- render_sequence_items(
311
- st.session_state[items_key],
312
- item_type,
313
- key,
314
- items_key,
315
- disabled,
316
- field_info,
317
- )
318
-
319
- return st.session_state[items_key]
320
-
321
-
322
- def render_sequence_items(
323
- items: list,
324
- item_type: Any,
325
- key: str,
326
- items_key: str,
327
- disabled: bool,
328
- field_info: dict,
329
- ) -> None:
330
- """Render items in a sequence with delete buttons."""
331
- item_info = field_info.copy()
332
- item_info["type"] = item_type
333
- item_info["inside_expander"] = True
298
+ from streambricks.widgets.sequence import sequence_widget
334
299
 
335
- try:
336
- renderer = get_field_renderer(item_info)
337
- items_to_delete = []
338
- for i, item in enumerate(items):
339
- st.divider()
340
- st.markdown(f"**Item {i + 1}**")
341
-
342
- # Render the item
343
- items[i] = renderer(
344
- key=f"{key}_item_{i}",
345
- value=item,
346
- label=f"Item {i + 1}",
347
- disabled=disabled,
348
- **item_info,
349
- )
350
-
351
- delete_key = f"{key}_delete_{i}"
352
- if st.button("Delete Item", key=delete_key, disabled=disabled):
353
- items_to_delete.append(i)
300
+ item_type = get_inner_type(field_info)
301
+ result = sequence_widget(
302
+ label=label or key,
303
+ item_type=item_type,
304
+ value=value, # type: ignore
305
+ key=key,
306
+ disabled=disabled,
307
+ help=help,
308
+ **field_info,
309
+ )
354
310
 
355
- if items_to_delete:
356
- for idx in sorted(items_to_delete, reverse=True):
357
- if 0 <= idx < len(items):
358
- items.pop(idx)
359
- st.rerun() # Force rerun after deletion
311
+ # Cast back to original sequence type if needed
312
+ annotation = field_info.get("type")
313
+ if annotation is tuple or (get_origin(annotation) is tuple):
314
+ return tuple(result)
360
315
 
361
- except Exception as e: # noqa: BLE001
362
- st.error(f"Error rendering sequence items: {e!s}")
316
+ return result
363
317
 
364
318
 
365
319
  def render_set_field(
@@ -0,0 +1,112 @@
1
+ """Sequence management widget for streamlit applications."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import streamlit as st
8
+
9
+ from streambricks.widgets.model_widget.main import get_field_renderer
10
+
11
+
12
+ def sequence_widget[T](
13
+ label: str,
14
+ item_type: type[T],
15
+ value: list[T] | None = None,
16
+ key: str | None = None,
17
+ disabled: bool = False,
18
+ help: str | None = None, # noqa: A002
19
+ **field_info: Any,
20
+ ) -> list[T]:
21
+ """Create a widget for managing sequences (lists) of items.
22
+
23
+ Args:
24
+ label: Label to display
25
+ item_type: Type of items in the sequence
26
+ value: Current sequence value
27
+ key: Optional unique key for widget state
28
+ disabled: Whether the widget is disabled
29
+ help: Help text to display
30
+ field_info: Additional field information
31
+
32
+ Returns:
33
+ Updated sequence of items
34
+ """
35
+ widget_key = key or label
36
+ items_key = f"{widget_key}_items"
37
+ add_item_key = f"{widget_key}_add_item"
38
+ if items_key not in st.session_state:
39
+ st.session_state[items_key] = list(value) if value is not None else []
40
+
41
+ label_col, widget_col = st.columns([1, 3])
42
+ with label_col:
43
+ st.markdown(f"**{label}**")
44
+ if help:
45
+ st.caption(help)
46
+
47
+ with widget_col:
48
+ if st.button("Add Item", key=add_item_key, disabled=disabled):
49
+ from streambricks.widgets.type_helpers import add_new_item
50
+
51
+ add_new_item(st.session_state[items_key], item_type)
52
+
53
+ items_to_delete = []
54
+ item_info = field_info.copy()
55
+ item_info["type"] = item_type
56
+
57
+ try:
58
+ renderer = get_field_renderer(item_info)
59
+ for i, item in enumerate(st.session_state[items_key]):
60
+ cols = st.columns([0.8, 0.2])
61
+ with cols[0]:
62
+ st.session_state[items_key][i] = renderer(
63
+ key=f"{widget_key}_item_{i}",
64
+ value=item,
65
+ label=f"Item {i + 1}",
66
+ disabled=disabled,
67
+ **item_info,
68
+ )
69
+ with cols[1]:
70
+ st.write("")
71
+ if st.button("🗑️", key=f"{widget_key}_delete_{i}", disabled=disabled):
72
+ items_to_delete.append(i)
73
+
74
+ if items_to_delete:
75
+ for idx in sorted(items_to_delete, reverse=True):
76
+ if 0 <= idx < len(st.session_state[items_key]):
77
+ st.session_state[items_key].pop(idx)
78
+ st.rerun()
79
+
80
+ except Exception as e: # noqa: BLE001
81
+ st.error(f"Error rendering sequence items: {e!s}")
82
+
83
+ return st.session_state[items_key]
84
+
85
+
86
+ if __name__ == "__main__":
87
+ from pydantic import BaseModel
88
+
89
+ from streambricks.helpers import run
90
+
91
+ class SubItem(BaseModel):
92
+ name: str = ""
93
+ value: int = 0
94
+
95
+ def demo():
96
+ st.title("Sequence Widget Demo")
97
+ numbers = sequence_widget(
98
+ "Numbers",
99
+ int,
100
+ value=[1, 2, 3],
101
+ help="A list of integers",
102
+ )
103
+ st.write("Current numbers:", numbers)
104
+ items = sequence_widget(
105
+ "Complex Items",
106
+ SubItem,
107
+ value=[SubItem(name="Item 1", value=42)],
108
+ help="A list of SubItems",
109
+ )
110
+ st.write("Current items:", [item.model_dump() for item in items])
111
+
112
+ run(demo)
@@ -1,48 +0,0 @@
1
- """Utility functions for Streamlit applications."""
2
-
3
- from __future__ import annotations
4
-
5
- import asyncio
6
- import inspect
7
- import sys
8
- from typing import TYPE_CHECKING, Any, TypeVar
9
-
10
- from streamlit import runtime
11
- from streamlit.web.cli import main
12
-
13
-
14
- if TYPE_CHECKING:
15
- from collections.abc import Callable, Coroutine
16
-
17
-
18
- T = TypeVar("T")
19
-
20
-
21
- def run(
22
- fn: Callable[..., T | Coroutine[Any, Any, T]] | Coroutine[Any, Any, T],
23
- *args: Any,
24
- **kwargs: Any,
25
- ) -> None:
26
- """Run a function or coroutine with Streamlit.
27
-
28
- If Streamlit runtime exists, execute the function directly. Otherwise,
29
- start Streamlit with the current script.
30
-
31
- Args:
32
- fn: The function or coroutine to run
33
- args: Positional arguments to pass to the function
34
- kwargs: Keyword arguments to pass to the function
35
- """
36
- if runtime.exists():
37
- if inspect.iscoroutine(fn):
38
- asyncio.run(fn)
39
- # Handle coroutine function
40
- elif inspect.iscoroutinefunction(fn):
41
- coro = fn(*args, **kwargs)
42
- asyncio.run(coro)
43
- # Handle regular function
44
- else:
45
- fn(*args, **kwargs) # type: ignore
46
- else:
47
- sys.argv = ["streamlit", "run", sys.argv[0]]
48
- sys.exit(main())
File without changes
File without changes
File without changes
File without changes
File without changes