streambricks 0.2.8__tar.gz → 0.2.9__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 (29) hide show
  1. {streambricks-0.2.8 → streambricks-0.2.9}/PKG-INFO +1 -1
  2. {streambricks-0.2.8 → streambricks-0.2.9}/src/streambricks/__init__.py +3 -1
  3. streambricks-0.2.9/src/streambricks/widgets/bind_kwargs.py +221 -0
  4. {streambricks-0.2.8 → streambricks-0.2.9}/src/streambricks/widgets/model_widget.py +79 -8
  5. {streambricks-0.2.8 → streambricks-0.2.9}/src/streambricks/widgets/type_helpers.py +9 -0
  6. {streambricks-0.2.8 → streambricks-0.2.9}/.copier-answers.yml +0 -0
  7. {streambricks-0.2.8 → streambricks-0.2.9}/.github/FUNDING.yml +0 -0
  8. {streambricks-0.2.8 → streambricks-0.2.9}/.github/copilot-instructions.md +0 -0
  9. {streambricks-0.2.8 → streambricks-0.2.9}/.github/dependabot.yml +0 -0
  10. {streambricks-0.2.8 → streambricks-0.2.9}/.github/workflows/build.yml +0 -0
  11. {streambricks-0.2.8 → streambricks-0.2.9}/.github/workflows/documentation.yml +0 -0
  12. {streambricks-0.2.8 → streambricks-0.2.9}/.gitignore +0 -0
  13. {streambricks-0.2.8 → streambricks-0.2.9}/.pre-commit-config.yaml +0 -0
  14. {streambricks-0.2.8 → streambricks-0.2.9}/LICENSE +0 -0
  15. {streambricks-0.2.8 → streambricks-0.2.9}/README.md +0 -0
  16. {streambricks-0.2.8 → streambricks-0.2.9}/docs/.empty +0 -0
  17. {streambricks-0.2.8 → streambricks-0.2.9}/duties.py +0 -0
  18. {streambricks-0.2.8 → streambricks-0.2.9}/mkdocs.yml +0 -0
  19. {streambricks-0.2.8 → streambricks-0.2.9}/overrides/_dummy.txt +0 -0
  20. {streambricks-0.2.8 → streambricks-0.2.9}/pyproject.toml +0 -0
  21. {streambricks-0.2.8 → streambricks-0.2.9}/src/streambricks/helpers.py +0 -0
  22. {streambricks-0.2.8 → streambricks-0.2.9}/src/streambricks/py.typed +0 -0
  23. {streambricks-0.2.8 → streambricks-0.2.9}/src/streambricks/state.py +0 -0
  24. {streambricks-0.2.8 → streambricks-0.2.9}/src/streambricks/widgets/__init__.py +0 -0
  25. {streambricks-0.2.8 → streambricks-0.2.9}/src/streambricks/widgets/model_selector.py +0 -0
  26. {streambricks-0.2.8 → streambricks-0.2.9}/src/streambricks/widgets/multi_select.py +0 -0
  27. {streambricks-0.2.8 → streambricks-0.2.9}/tests/__init__.py +0 -0
  28. {streambricks-0.2.8 → streambricks-0.2.9}/tests/conftest.py +0 -0
  29. {streambricks-0.2.8 → streambricks-0.2.9}/tests/test_widgets.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: streambricks
3
- Version: 0.2.8
3
+ Version: 0.2.9
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,4 +1,4 @@
1
- __version__ = "0.2.8"
1
+ __version__ = "0.2.9"
2
2
 
3
3
 
4
4
  from streambricks.widgets.model_widget import (
@@ -12,10 +12,12 @@ from streambricks.widgets.model_selector import (
12
12
  )
13
13
  from streambricks.helpers import run
14
14
  from streambricks.state import State
15
+ from streambricks.widgets.bind_kwargs import bind_kwargs_as_widget
15
16
 
16
17
  __all__ = [
17
18
  "MultiSelectItem",
18
19
  "State",
20
+ "bind_kwargs_as_widget",
19
21
  "llm_model_selector",
20
22
  "model_display",
21
23
  "model_edit",
@@ -0,0 +1,221 @@
1
+ """Widget binder that exposes function kwargs as configurable widgets."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from functools import wraps
6
+ from inspect import Parameter, signature
7
+ from typing import TYPE_CHECKING, Any, ParamSpec, TypeVar
8
+
9
+ from pydantic import Field, create_model
10
+ import streamlit as st
11
+
12
+ from streambricks.widgets.model_widget import render_model_form
13
+
14
+
15
+ if TYPE_CHECKING:
16
+ from collections.abc import Callable
17
+
18
+
19
+ T = TypeVar("T")
20
+ P = ParamSpec("P")
21
+
22
+
23
+ def bind_kwargs_as_widget(
24
+ func: Callable[P, T],
25
+ *,
26
+ kwargs_to_bind: list[str],
27
+ widget_prefix: str = "",
28
+ title: str | None = None,
29
+ ) -> Callable[P, T]:
30
+ """Bind function kwargs as Streamlit widgets.
31
+
32
+ Creates a new function that wraps the original, displaying configurable
33
+ widgets for the specified kwargs before executing the original function.
34
+
35
+ Args:
36
+ func: The function whose kwargs should be exposed as widgets
37
+ kwargs_to_bind: List of kwarg names to expose as widgets
38
+ widget_prefix: Prefix for widget keys to avoid conflicts
39
+ title: Optional title to display above the widgets
40
+
41
+ Returns:
42
+ A new function that wraps the original with widget-configurable kwargs
43
+ """
44
+ # Get function signature
45
+ sig = signature(func)
46
+
47
+ # Create a dynamic model for the kwargs we want to expose
48
+ fields = {}
49
+ defaults = {}
50
+ docstrings = {}
51
+
52
+ # Extract parameter annotations and docstrings from function
53
+ func_doc = func.__doc__ or ""
54
+ param_docs = {}
55
+
56
+ # Very simple docstring parser for param descriptions
57
+ if func_doc:
58
+ lines = func_doc.split("\n")
59
+ in_params = False
60
+ current_param = None
61
+
62
+ for line in lines:
63
+ line = line.strip()
64
+
65
+ # Check for param section markers
66
+ if line.lower() in ("parameters:", "args:", "arguments:"):
67
+ in_params = True
68
+ continue
69
+
70
+ if in_params and line and line[0] == ":":
71
+ # Handle :param name: description format
72
+ if line.startswith(":param "):
73
+ parts = line[7:].split(":", 1)
74
+ if len(parts) == 2: # noqa: PLR2004
75
+ param_name = parts[0].strip()
76
+ param_docs[param_name] = parts[1].strip()
77
+ current_param = param_name
78
+ # Handle :return: which ends the params section
79
+ elif line.startswith(":return"):
80
+ in_params = False
81
+ # Handle continued description on next line
82
+ elif current_param:
83
+ param_docs[current_param] += " " + line
84
+ elif in_params and line and line[0] != ":":
85
+ # Standard format: param_name: description
86
+ if ":" in line:
87
+ parts = line.split(":", 1)
88
+ param_name = parts[0].strip()
89
+ param_docs[param_name] = parts[1].strip()
90
+ current_param = param_name
91
+ # Handle continued description on next line
92
+ elif current_param:
93
+ param_docs[current_param] += " " + line
94
+
95
+ # Extract field types and defaults from function signature
96
+ for name, param in sig.parameters.items():
97
+ if name in kwargs_to_bind:
98
+ param_type = param.annotation if param.annotation != Parameter.empty else Any
99
+ default = param.default if param.default != Parameter.empty else None
100
+
101
+ # Handle special case: Optional types
102
+ if param_type.__class__.__name__ == "_UnionGenericAlias": # pyright: ignore
103
+ # For Union[X, None] types (Optional[X])
104
+ args = getattr(param_type, "__args__", ())
105
+ if len(args) == 2 and args[1] is type(None): # noqa: PLR2004
106
+ param_type = args[0]
107
+
108
+ # Create field with appropriate defaults and metadata
109
+ field_kwargs = {"default": default}
110
+
111
+ # Add description from docstring if available
112
+ if name in param_docs:
113
+ field_kwargs["description"] = param_docs[name]
114
+ docstrings[name] = param_docs[name]
115
+
116
+ fields[name] = (param_type, Field(**field_kwargs)) # pyright: ignore
117
+ if default != Parameter.empty:
118
+ defaults[name] = default
119
+
120
+ # Create a Pydantic model dynamically
121
+ model_name = f"{func.__name__}Config"
122
+ config_model = create_model(model_name, **fields)
123
+
124
+ # Add docstrings as class variables
125
+ for name, docstring in docstrings.items():
126
+ setattr(config_model, f"__doc_{name}__", docstring)
127
+
128
+ # Create a session state key for storing current config
129
+ config_key = f"{widget_prefix}_{func.__name__}_config"
130
+
131
+ @wraps(func)
132
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
133
+ # Initialize config in session state if needed
134
+ if config_key not in st.session_state:
135
+ # Initialize with defaults
136
+ config_data = {
137
+ name: (defaults.get(name))
138
+ for name in kwargs_to_bind
139
+ if name in sig.parameters
140
+ }
141
+ # Override with any provided values in kwargs
142
+ for name in kwargs_to_bind:
143
+ if name in kwargs:
144
+ config_data[name] = kwargs[name]
145
+
146
+ st.session_state[config_key] = config_model(**config_data)
147
+
148
+ # Display title if provided
149
+ if title:
150
+ st.subheader(title)
151
+
152
+ # Render config form
153
+ updated_config = render_model_form(st.session_state[config_key])
154
+ st.session_state[config_key] = updated_config
155
+
156
+ # Update kwargs with values from the form
157
+ for name in kwargs_to_bind:
158
+ if hasattr(updated_config, name):
159
+ kwargs[name] = getattr(updated_config, name)
160
+
161
+ # Call the original function
162
+ return func(*args, **kwargs)
163
+
164
+ return wrapper
165
+
166
+
167
+ if __name__ == "__main__":
168
+ from typing import Any, Literal
169
+
170
+ import streamlit as st
171
+
172
+ from streambricks.helpers import run
173
+
174
+ def complex_function(
175
+ a: int,
176
+ b: str,
177
+ show_details: bool = False,
178
+ format_type: Literal["simple", "detailed", "compact"] = "simple",
179
+ max_items: int = 5,
180
+ threshold: float = 0.75,
181
+ ) -> None:
182
+ """Function with various kwargs that can be configured via widgets.
183
+
184
+ Args:
185
+ a: First parameter value
186
+ b: Second parameter string
187
+ show_details: Whether to show additional details
188
+ format_type: The format to use for display
189
+ max_items: Maximum number of items to show
190
+ threshold: Threshold value for filtering
191
+ """
192
+ st.write(f"Regular args: a={a}, b={b}")
193
+ st.write(f"Format type: {format_type}")
194
+
195
+ if show_details:
196
+ st.write("Details enabled!")
197
+ st.write(f"Threshold: {threshold}")
198
+
199
+ st.write(f"Showing {max_items} items:")
200
+ for i in range(max_items):
201
+ st.write(f"Item {i + 1}")
202
+
203
+ # Bind specific kwargs to widgets
204
+ configurable_function = bind_kwargs_as_widget(
205
+ complex_function,
206
+ kwargs_to_bind=["show_details", "format_type", "max_items", "threshold"],
207
+ title="Configure Function",
208
+ )
209
+
210
+ def demo():
211
+ st.title("Bind Args as Widget Demo")
212
+
213
+ # Regular inputs for non-widget args
214
+ a = st.number_input("Value for a", value=10)
215
+ b = st.text_input("Value for b", value="hello")
216
+
217
+ # This will display widgets for the bound kwargs
218
+ # and then call the function with those values
219
+ configurable_function(a, b)
220
+
221
+ run(demo)
@@ -45,19 +45,27 @@ def render_str_field(
45
45
  """Render a string field using appropriate Streamlit widget."""
46
46
  max_length = field_info.get("max_length", 0)
47
47
  multiple_lines = field_info.get("multiple_lines", False)
48
+ safe_value = "" if value is None else value
49
+ has_meaningful_content = safe_value.strip() != ""
50
+ has_line_breaks = has_meaningful_content and (
51
+ "\n" in safe_value or "\r" in safe_value
52
+ )
53
+ is_long_val = len(safe_value) > 100 # noqa: PLR2004
54
+ use_text_area = max_length > 100 or is_long_val or multiple_lines or has_line_breaks # noqa: PLR2004
48
55
 
49
- if max_length > 100 or multiple_lines: # noqa: PLR2004
56
+ if use_text_area:
50
57
  return st.text_area(
51
58
  label=label or key,
52
- value=value or "",
59
+ value=safe_value,
53
60
  disabled=disabled,
54
61
  key=key,
55
62
  help=help,
56
63
  )
57
64
 
65
+ # For single-line inputs, strip whitespace as it's usually unintentional
58
66
  return st.text_input(
59
67
  label=label or key,
60
- value=value or "",
68
+ value=safe_value.strip() if has_meaningful_content else safe_value,
61
69
  disabled=disabled,
62
70
  key=key,
63
71
  help=help,
@@ -746,6 +754,63 @@ def display_set_readonly(value, field_type, key=None):
746
754
  display_value_readonly(item, item_type, key=f"{key}_{i}" if key else None)
747
755
 
748
756
 
757
+ def wrap_as_optional_field(renderer: WidgetFunc) -> WidgetFunc:
758
+ """Wrap a field renderer with None toggle functionality.
759
+
760
+ Args:
761
+ renderer: The inner renderer function
762
+
763
+ Returns:
764
+ A new renderer that handles None values with a toggle
765
+ """
766
+
767
+ def optional_wrapper(
768
+ *,
769
+ key: str,
770
+ value: Any = None,
771
+ label: str | None = None,
772
+ disabled: bool = False,
773
+ help: str | None = None, # noqa: A002
774
+ **field_info: Any,
775
+ ) -> Any:
776
+ # Create a layout for the field
777
+ enable_key = f"{key}_enable"
778
+
779
+ # Create columns for checkbox and content
780
+ cols = st.columns([0.1, 0.9])
781
+
782
+ # Toggle checkbox in first column
783
+ with cols[0]:
784
+ is_enabled = st.checkbox(
785
+ "Enable",
786
+ value=value is not None,
787
+ key=enable_key,
788
+ disabled=disabled,
789
+ label_visibility="collapsed",
790
+ )
791
+
792
+ # Content in second column
793
+ with cols[1]:
794
+ # Show field label
795
+ st.markdown(f"**{label or key}**")
796
+ if help:
797
+ st.caption(help)
798
+
799
+ # If enabled, render the field; otherwise show "None"
800
+ if is_enabled:
801
+ return renderer(
802
+ key=key,
803
+ value=value,
804
+ label="", # We've already shown the label
805
+ disabled=disabled,
806
+ **field_info,
807
+ )
808
+ st.text("None")
809
+ return None
810
+
811
+ return optional_wrapper
812
+
813
+
749
814
  def render_model_instance_field(
750
815
  *,
751
816
  key: str,
@@ -1116,19 +1181,25 @@ if __name__ == "__main__":
1116
1181
 
1117
1182
  status: int | str | bool = 2
1118
1183
  """A field that can be either int, str, or bool."""
1119
-
1120
- optional_text: bool = True
1184
+ boolean: bool = True
1121
1185
  """Optional text field."""
1186
+ long_text: str | None = "test " * 40
1187
+ """Long text."""
1188
+
1189
+ # Fields that demonstrate the optional toggle
1190
+ optional_int: int | None = None
1191
+ """An optional integer that can be None."""
1192
+ optional_string: str | None = None
1193
+ """An optional string that can be None."""
1194
+ optional_model: SubModel | None = None
1195
+ """An optional nested model that can be None."""
1122
1196
 
1123
1197
  tags: list[str] = Field(default_factory=list)
1124
1198
  """A list of string tags."""
1125
-
1126
1199
  numbers: list[int | float] = Field(default_factory=list)
1127
1200
  """A list of numbers (int or float)"""
1128
-
1129
1201
  settings: list[SubModel] = Field(default_factory=list)
1130
1202
  """A list of nested models"""
1131
-
1132
1203
  priorities: list[Literal["Low", "Medium", "High"]] = Field(default_factory=list)
1133
1204
  """A list of priority levels."""
1134
1205
 
@@ -26,6 +26,15 @@ def is_union_type(annotation: Any) -> bool:
26
26
  )
27
27
 
28
28
 
29
+ def is_optional_type(annotation: Any) -> bool:
30
+ """Check if a type annotation is an Optional type (T | None)."""
31
+ if not is_union_type(annotation):
32
+ return False
33
+
34
+ args = get_args(annotation)
35
+ return type(None) in args
36
+
37
+
29
38
  def is_set_type(annotation: Any) -> bool:
30
39
  """Check if the annotation represents a set type."""
31
40
  if annotation is set:
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes