streambricks 0.2.8__tar.gz → 0.2.10__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.10}/PKG-INFO +1 -1
  2. {streambricks-0.2.8 → streambricks-0.2.10}/src/streambricks/__init__.py +3 -1
  3. streambricks-0.2.10/src/streambricks/widgets/bind_kwargs.py +221 -0
  4. {streambricks-0.2.8 → streambricks-0.2.10}/src/streambricks/widgets/model_widget.py +114 -8
  5. {streambricks-0.2.8 → streambricks-0.2.10}/src/streambricks/widgets/type_helpers.py +9 -0
  6. {streambricks-0.2.8 → streambricks-0.2.10}/.copier-answers.yml +0 -0
  7. {streambricks-0.2.8 → streambricks-0.2.10}/.github/FUNDING.yml +0 -0
  8. {streambricks-0.2.8 → streambricks-0.2.10}/.github/copilot-instructions.md +0 -0
  9. {streambricks-0.2.8 → streambricks-0.2.10}/.github/dependabot.yml +0 -0
  10. {streambricks-0.2.8 → streambricks-0.2.10}/.github/workflows/build.yml +0 -0
  11. {streambricks-0.2.8 → streambricks-0.2.10}/.github/workflows/documentation.yml +0 -0
  12. {streambricks-0.2.8 → streambricks-0.2.10}/.gitignore +0 -0
  13. {streambricks-0.2.8 → streambricks-0.2.10}/.pre-commit-config.yaml +0 -0
  14. {streambricks-0.2.8 → streambricks-0.2.10}/LICENSE +0 -0
  15. {streambricks-0.2.8 → streambricks-0.2.10}/README.md +0 -0
  16. {streambricks-0.2.8 → streambricks-0.2.10}/docs/.empty +0 -0
  17. {streambricks-0.2.8 → streambricks-0.2.10}/duties.py +0 -0
  18. {streambricks-0.2.8 → streambricks-0.2.10}/mkdocs.yml +0 -0
  19. {streambricks-0.2.8 → streambricks-0.2.10}/overrides/_dummy.txt +0 -0
  20. {streambricks-0.2.8 → streambricks-0.2.10}/pyproject.toml +0 -0
  21. {streambricks-0.2.8 → streambricks-0.2.10}/src/streambricks/helpers.py +0 -0
  22. {streambricks-0.2.8 → streambricks-0.2.10}/src/streambricks/py.typed +0 -0
  23. {streambricks-0.2.8 → streambricks-0.2.10}/src/streambricks/state.py +0 -0
  24. {streambricks-0.2.8 → streambricks-0.2.10}/src/streambricks/widgets/__init__.py +0 -0
  25. {streambricks-0.2.8 → streambricks-0.2.10}/src/streambricks/widgets/model_selector.py +0 -0
  26. {streambricks-0.2.8 → streambricks-0.2.10}/src/streambricks/widgets/multi_select.py +0 -0
  27. {streambricks-0.2.8 → streambricks-0.2.10}/tests/__init__.py +0 -0
  28. {streambricks-0.2.8 → streambricks-0.2.10}/tests/conftest.py +0 -0
  29. {streambricks-0.2.8 → streambricks-0.2.10}/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.10
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.10"
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)
@@ -32,6 +32,33 @@ if TYPE_CHECKING:
32
32
  T = TypeVar("T")
33
33
  WidgetFunc = Callable[..., T]
34
34
 
35
+ FIELD_METADATA_RENDERERS: dict[str, WidgetFunc[Any]] = {}
36
+
37
+
38
+ def register_field_renderer(field_type: str, renderer: WidgetFunc[Any]) -> None:
39
+ """Register a custom field renderer for a specific field_type."""
40
+ FIELD_METADATA_RENDERERS[field_type] = renderer
41
+
42
+
43
+ def render_model_identifier_field(
44
+ *,
45
+ key: str,
46
+ value: str | None = None,
47
+ label: str | None = None,
48
+ disabled: bool = False,
49
+ help: str | None = None, # noqa: A002
50
+ **field_info: Any,
51
+ ) -> str:
52
+ """Render a model identifier field using model_selector widget."""
53
+ from streambricks.widgets.model_selector import model_selector
54
+
55
+ providers = field_info.get("providers")
56
+ selected_model = model_selector(value=value, providers=providers, expanded=False)
57
+ return selected_model.pydantic_ai_id if selected_model else value or ""
58
+
59
+
60
+ register_field_renderer("model_identifier", render_model_identifier_field)
61
+
35
62
 
36
63
  def render_str_field(
37
64
  *,
@@ -45,19 +72,27 @@ def render_str_field(
45
72
  """Render a string field using appropriate Streamlit widget."""
46
73
  max_length = field_info.get("max_length", 0)
47
74
  multiple_lines = field_info.get("multiple_lines", False)
75
+ safe_value = "" if value is None else value
76
+ has_meaningful_content = safe_value.strip() != ""
77
+ has_line_breaks = has_meaningful_content and (
78
+ "\n" in safe_value or "\r" in safe_value
79
+ )
80
+ is_long_val = len(safe_value) > 100 # noqa: PLR2004
81
+ use_text_area = max_length > 100 or is_long_val or multiple_lines or has_line_breaks # noqa: PLR2004
48
82
 
49
- if max_length > 100 or multiple_lines: # noqa: PLR2004
83
+ if use_text_area:
50
84
  return st.text_area(
51
85
  label=label or key,
52
- value=value or "",
86
+ value=safe_value,
53
87
  disabled=disabled,
54
88
  key=key,
55
89
  help=help,
56
90
  )
57
91
 
92
+ # For single-line inputs, strip whitespace as it's usually unintentional
58
93
  return st.text_input(
59
94
  label=label or key,
60
- value=value or "",
95
+ value=safe_value.strip() if has_meaningful_content else safe_value,
61
96
  disabled=disabled,
62
97
  key=key,
63
98
  help=help,
@@ -746,6 +781,63 @@ def display_set_readonly(value, field_type, key=None):
746
781
  display_value_readonly(item, item_type, key=f"{key}_{i}" if key else None)
747
782
 
748
783
 
784
+ def wrap_as_optional_field(renderer: WidgetFunc) -> WidgetFunc:
785
+ """Wrap a field renderer with None toggle functionality.
786
+
787
+ Args:
788
+ renderer: The inner renderer function
789
+
790
+ Returns:
791
+ A new renderer that handles None values with a toggle
792
+ """
793
+
794
+ def optional_wrapper(
795
+ *,
796
+ key: str,
797
+ value: Any = None,
798
+ label: str | None = None,
799
+ disabled: bool = False,
800
+ help: str | None = None, # noqa: A002
801
+ **field_info: Any,
802
+ ) -> Any:
803
+ # Create a layout for the field
804
+ enable_key = f"{key}_enable"
805
+
806
+ # Create columns for checkbox and content
807
+ cols = st.columns([0.1, 0.9])
808
+
809
+ # Toggle checkbox in first column
810
+ with cols[0]:
811
+ is_enabled = st.checkbox(
812
+ "Enable",
813
+ value=value is not None,
814
+ key=enable_key,
815
+ disabled=disabled,
816
+ label_visibility="collapsed",
817
+ )
818
+
819
+ # Content in second column
820
+ with cols[1]:
821
+ # Show field label
822
+ st.markdown(f"**{label or key}**")
823
+ if help:
824
+ st.caption(help)
825
+
826
+ # If enabled, render the field; otherwise show "None"
827
+ if is_enabled:
828
+ return renderer(
829
+ key=key,
830
+ value=value,
831
+ label="", # We've already shown the label
832
+ disabled=disabled,
833
+ **field_info,
834
+ )
835
+ st.text("None")
836
+ return None
837
+
838
+ return optional_wrapper
839
+
840
+
749
841
  def render_model_instance_field(
750
842
  *,
751
843
  key: str,
@@ -826,6 +918,14 @@ PRIMITIVE_RENDERERS = {
826
918
  def get_field_renderer(field_info: dict[str, Any]) -> WidgetFunc[Any]: # noqa: PLR0911
827
919
  """Get the appropriate renderer for a field based on its type and constraints."""
828
920
  annotation = field_info.get("type") or field_info.get("annotation")
921
+ # Check for custom field type specification in json_schema_extra
922
+ json_schema_extra = field_info.get("json_schema_extra", {})
923
+ if (
924
+ json_schema_extra
925
+ and (field_type := json_schema_extra.get("field_type"))
926
+ in FIELD_METADATA_RENDERERS
927
+ ):
928
+ return FIELD_METADATA_RENDERERS[field_type]
829
929
  if annotation is SecretStr or (
830
930
  isinstance(annotation, type) and issubclass(annotation, SecretStr)
831
931
  ):
@@ -1116,19 +1216,25 @@ if __name__ == "__main__":
1116
1216
 
1117
1217
  status: int | str | bool = 2
1118
1218
  """A field that can be either int, str, or bool."""
1119
-
1120
- optional_text: bool = True
1219
+ boolean: bool = True
1121
1220
  """Optional text field."""
1221
+ long_text: str | None = "test " * 40
1222
+ """Long text."""
1223
+
1224
+ # Fields that demonstrate the optional toggle
1225
+ optional_int: int | None = None
1226
+ """An optional integer that can be None."""
1227
+ optional_string: str | None = None
1228
+ """An optional string that can be None."""
1229
+ optional_model: SubModel | None = None
1230
+ """An optional nested model that can be None."""
1122
1231
 
1123
1232
  tags: list[str] = Field(default_factory=list)
1124
1233
  """A list of string tags."""
1125
-
1126
1234
  numbers: list[int | float] = Field(default_factory=list)
1127
1235
  """A list of numbers (int or float)"""
1128
-
1129
1236
  settings: list[SubModel] = Field(default_factory=list)
1130
1237
  """A list of nested models"""
1131
-
1132
1238
  priorities: list[Literal["Low", "Medium", "High"]] = Field(default_factory=list)
1133
1239
  """A list of priority levels."""
1134
1240
 
@@ -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