streambricks 0.2.1__tar.gz → 0.2.2__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 (28) hide show
  1. {streambricks-0.2.1 → streambricks-0.2.2}/.pre-commit-config.yaml +1 -1
  2. {streambricks-0.2.1 → streambricks-0.2.2}/PKG-INFO +1 -1
  3. streambricks-0.2.2/src/streambricks/__init__.py +23 -0
  4. {streambricks-0.2.1 → streambricks-0.2.2}/src/streambricks/widgets/model_selector.py +4 -4
  5. {streambricks-0.2.1 → streambricks-0.2.2}/src/streambricks/widgets/model_widget.py +247 -42
  6. {streambricks-0.2.1 → streambricks-0.2.2}/src/streambricks/widgets/type_helpers.py +13 -8
  7. streambricks-0.2.1/src/streambricks/__init__.py +0 -16
  8. {streambricks-0.2.1 → streambricks-0.2.2}/.copier-answers.yml +0 -0
  9. {streambricks-0.2.1 → streambricks-0.2.2}/.github/FUNDING.yml +0 -0
  10. {streambricks-0.2.1 → streambricks-0.2.2}/.github/copilot-instructions.md +0 -0
  11. {streambricks-0.2.1 → streambricks-0.2.2}/.github/dependabot.yml +0 -0
  12. {streambricks-0.2.1 → streambricks-0.2.2}/.github/workflows/build.yml +0 -0
  13. {streambricks-0.2.1 → streambricks-0.2.2}/.github/workflows/documentation.yml +0 -0
  14. {streambricks-0.2.1 → streambricks-0.2.2}/.gitignore +0 -0
  15. {streambricks-0.2.1 → streambricks-0.2.2}/LICENSE +0 -0
  16. {streambricks-0.2.1 → streambricks-0.2.2}/README.md +0 -0
  17. {streambricks-0.2.1 → streambricks-0.2.2}/docs/.empty +0 -0
  18. {streambricks-0.2.1 → streambricks-0.2.2}/duties.py +0 -0
  19. {streambricks-0.2.1 → streambricks-0.2.2}/mkdocs.yml +0 -0
  20. {streambricks-0.2.1 → streambricks-0.2.2}/overrides/_dummy.txt +0 -0
  21. {streambricks-0.2.1 → streambricks-0.2.2}/pyproject.toml +0 -0
  22. {streambricks-0.2.1 → streambricks-0.2.2}/src/streambricks/helpers.py +0 -0
  23. {streambricks-0.2.1 → streambricks-0.2.2}/src/streambricks/py.typed +0 -0
  24. {streambricks-0.2.1 → streambricks-0.2.2}/src/streambricks/widgets/__init__.py +0 -0
  25. {streambricks-0.2.1 → streambricks-0.2.2}/src/streambricks/widgets/multi_select.py +0 -0
  26. {streambricks-0.2.1 → streambricks-0.2.2}/tests/__init__.py +0 -0
  27. {streambricks-0.2.1 → streambricks-0.2.2}/tests/conftest.py +0 -0
  28. {streambricks-0.2.1 → streambricks-0.2.2}/tests/test_widgets.py +0 -0
@@ -35,7 +35,7 @@ repos:
35
35
  additional_dependencies: [orjson]
36
36
 
37
37
  - repo: https://github.com/charliermarsh/ruff-pre-commit
38
- rev: v0.11.0
38
+ rev: v0.11.2
39
39
  hooks:
40
40
  - id: ruff
41
41
  - id: ruff-format
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: streambricks
3
- Version: 0.2.1
3
+ Version: 0.2.2
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
@@ -0,0 +1,23 @@
1
+ __version__ = "0.2.2"
2
+
3
+
4
+ from streambricks.widgets.model_widget import (
5
+ render_model_form as model_edit,
6
+ render_model_readonly as model_display,
7
+ )
8
+ from streambricks.widgets.multi_select import multiselect, MultiSelectItem
9
+ from streambricks.widgets.model_selector import (
10
+ model_selector,
11
+ model_selector as llm_model_selector,
12
+ )
13
+ from streambricks.helpers import run
14
+
15
+ __all__ = [
16
+ "MultiSelectItem",
17
+ "llm_model_selector",
18
+ "model_display",
19
+ "model_edit",
20
+ "model_selector",
21
+ "multiselect",
22
+ "run",
23
+ ]
@@ -15,14 +15,14 @@ if TYPE_CHECKING:
15
15
 
16
16
  def model_selector(
17
17
  *,
18
- initial_model: str | None = None,
18
+ value: str | None = None,
19
19
  providers: Sequence[ProviderType] | None = None,
20
20
  expanded: bool = True,
21
21
  ) -> ModelInfo | None:
22
22
  """Render a model selector with provider and model dropdowns.
23
23
 
24
24
  Args:
25
- initial_model: Initial model name to select
25
+ value: Initial model name to select
26
26
  providers: List of providers to show models from
27
27
  expanded: Whether to expand the model details by default
28
28
 
@@ -35,9 +35,9 @@ def model_selector(
35
35
  available_providers = sorted({model.provider for model in models})
36
36
  current_model = None
37
37
  current_provider = None
38
- if initial_model:
38
+ if value:
39
39
  current_model = next(
40
- (m for m in models if m.pydantic_ai_id == initial_model),
40
+ (m for m in models if m.pydantic_ai_id == value),
41
41
  None,
42
42
  )
43
43
  if current_model:
@@ -20,6 +20,7 @@ from streambricks.widgets.type_helpers import (
20
20
  is_dataclass_like,
21
21
  is_literal_type,
22
22
  is_sequence_type,
23
+ is_set_type,
23
24
  is_union_type,
24
25
  )
25
26
 
@@ -474,6 +475,216 @@ def render_sequence_items(
474
475
  st.error(f"Error rendering sequence items: {e!s}")
475
476
 
476
477
 
478
+ def render_set_field(
479
+ *,
480
+ key: str,
481
+ value: set[Any] | None = None,
482
+ label: str | None = None,
483
+ disabled: bool = False,
484
+ help: str | None = None, # noqa: A002
485
+ **field_info: Any,
486
+ ) -> set[Any]:
487
+ """Render a field for set types with a multi-select interface when possible."""
488
+ annotation = field_info.get("type") or field_info.get("annotation")
489
+
490
+ # Initialize empty set if value is None
491
+ if value is None:
492
+ value = set()
493
+
494
+ # Extract item type from set annotation
495
+ try:
496
+ item_type = get_args(annotation)[0] # Get type of set items
497
+ except (IndexError, TypeError):
498
+ item_type = Any
499
+
500
+ # Check if item_type is an enum or literal - if so, we know all possible values
501
+ if (isinstance(item_type, type) and issubclass(item_type, Enum)) or is_literal_type(
502
+ item_type
503
+ ):
504
+ return render_set_with_known_domain(
505
+ key=key,
506
+ value=value,
507
+ item_type=item_type,
508
+ label=label,
509
+ disabled=disabled,
510
+ help=help,
511
+ )
512
+
513
+ # For open-ended sets, use a modified sequence renderer that ensures uniqueness
514
+ return render_open_set_field(
515
+ key=key,
516
+ value=value,
517
+ item_type=item_type,
518
+ label=label,
519
+ disabled=disabled,
520
+ help=help,
521
+ **field_info,
522
+ )
523
+
524
+
525
+ def render_set_with_known_domain(
526
+ *,
527
+ key: str,
528
+ value: set[Any],
529
+ item_type: Any,
530
+ label: str | None = None,
531
+ disabled: bool = False,
532
+ help: str | None = None, # noqa: A002
533
+ ) -> set[Any]:
534
+ """Render a set field using a multiselect when domain is known (enum or literal)."""
535
+ # Get all possible values
536
+ if isinstance(item_type, type) and issubclass(item_type, Enum):
537
+ all_options = list(item_type.__members__.values())
538
+ format_func = lambda x: x.name # noqa: E731
539
+ else: # Literal type
540
+ all_options = list(get_args(item_type))
541
+ format_func = str
542
+
543
+ # Use multi-select for known domain
544
+ selected = st.multiselect(
545
+ label=label or key,
546
+ options=all_options,
547
+ default=list(value),
548
+ format_func=format_func,
549
+ disabled=disabled,
550
+ key=key,
551
+ help=help,
552
+ )
553
+ return set(selected)
554
+
555
+
556
+ def render_open_set_field(
557
+ *,
558
+ key: str,
559
+ value: set[Any],
560
+ item_type: Any,
561
+ label: str | None = None,
562
+ disabled: bool = False,
563
+ help: str | None = None, # noqa: A002
564
+ **field_info: Any,
565
+ ) -> set[Any]:
566
+ """Render an open-ended set field with uniqueness enforcement."""
567
+ # Create unique state keys for this field
568
+ add_item_key = f"{key}_add_item"
569
+ items_key = f"{key}_items"
570
+
571
+ # Initialize session state for this field
572
+ if items_key not in st.session_state:
573
+ st.session_state[items_key] = list(value)
574
+
575
+ # Create container for set elements
576
+ st.markdown(f"**{label or key}**")
577
+ if help:
578
+ st.caption(help)
579
+
580
+ with st.container():
581
+ if st.button("Add Item", key=add_item_key, disabled=disabled):
582
+ temp_list: list[Any] = []
583
+ add_new_item(temp_list, item_type)
584
+
585
+ # If the temp_list has an item and it's not a duplicate, add it to our items
586
+ if temp_list and str(temp_list[0]) not in {
587
+ str(i) for i in st.session_state[items_key]
588
+ }:
589
+ st.session_state[items_key].append(temp_list[0])
590
+ elif temp_list: # Item was created but was a duplicate
591
+ st.warning("Item already exists in the set.")
592
+
593
+ render_set_items(
594
+ st.session_state[items_key],
595
+ item_type,
596
+ key,
597
+ items_key,
598
+ disabled,
599
+ field_info,
600
+ )
601
+
602
+ # Return the current items as a set
603
+ return set(st.session_state[items_key])
604
+
605
+
606
+ def render_set_items(
607
+ items: list,
608
+ item_type: Any,
609
+ key: str,
610
+ items_key: str,
611
+ disabled: bool,
612
+ field_info: dict,
613
+ ) -> None:
614
+ """Render items in a set with delete buttons and uniqueness enforcement."""
615
+ item_info = field_info.copy()
616
+ item_info["type"] = item_type
617
+ item_info["inside_expander"] = True # Mark as inside a container
618
+
619
+ try:
620
+ renderer = get_field_renderer(item_info)
621
+ items_to_delete = []
622
+
623
+ for i, item in enumerate(items):
624
+ st.divider()
625
+ st.markdown(f"**Item {i + 1}**")
626
+
627
+ # Render the item
628
+ updated_item = renderer(
629
+ key=f"{key}_item_{i}",
630
+ value=item,
631
+ label=f"Item {i + 1}",
632
+ disabled=disabled,
633
+ **item_info,
634
+ )
635
+
636
+ # Check if this update would create a duplicate
637
+ duplicate = False
638
+ for j, other_item in enumerate(items):
639
+ if i != j and str(updated_item) == str(other_item):
640
+ duplicate = True
641
+ break
642
+
643
+ if duplicate:
644
+ st.error("This value would create a duplicate in the set.")
645
+ else:
646
+ items[i] = updated_item
647
+
648
+ delete_key = f"{key}_delete_{i}"
649
+ if st.button("Delete Item", key=delete_key, disabled=disabled):
650
+ items_to_delete.append(i)
651
+
652
+ if items_to_delete:
653
+ for idx in sorted(items_to_delete, reverse=True):
654
+ if 0 <= idx < len(items):
655
+ items.pop(idx)
656
+ st.rerun() # Force rerun after deletion
657
+
658
+ except Exception as e: # noqa: BLE001
659
+ st.error(f"Error rendering set items: {e!s}")
660
+
661
+
662
+ def display_set_readonly(value, field_type, key=None):
663
+ """Display a set in read-only mode."""
664
+ if not value: # Empty set
665
+ st.text("No items")
666
+ return
667
+
668
+ item_type = Any
669
+ with contextlib.suppress(IndexError, TypeError):
670
+ item_type = get_args(field_type)[0]
671
+
672
+ # For known domain sets (enum or literal), show as comma-separated list
673
+ if (isinstance(item_type, type) and issubclass(item_type, Enum)) or is_literal_type(
674
+ item_type
675
+ ):
676
+ if isinstance(item_type, type) and issubclass(item_type, Enum):
677
+ display_text = ", ".join(item.name for item in value)
678
+ else:
679
+ display_text = ", ".join(str(item) for item in value)
680
+ st.text(display_text)
681
+ # For other sets, use the same expander approach as sequences
682
+ else:
683
+ for i, item in enumerate(value):
684
+ with st.expander(f"Item {i + 1}", expanded=False):
685
+ display_value_readonly(item, item_type, key=f"{key}_{i}" if key else None)
686
+
687
+
477
688
  def render_model_instance_field(
478
689
  *,
479
690
  key: str,
@@ -563,6 +774,9 @@ def get_field_renderer(field_info: dict[str, Any]) -> WidgetFunc[Any]: # noqa:
563
774
  if is_union_type(annotation):
564
775
  return render_union_field
565
776
 
777
+ if is_set_type(annotation):
778
+ return render_set_field
779
+
566
780
  if is_sequence_type(annotation):
567
781
  return render_sequence_field
568
782
 
@@ -642,34 +856,37 @@ def display_value_readonly(value, field_type, key=None):
642
856
  st.text("—") # Em dash to indicate empty value
643
857
  return
644
858
 
645
- # Handle collections (lists, sets, etc.)
859
+ if is_set_type(field_type):
860
+ display_set_readonly(value, field_type, key)
861
+ return
862
+
646
863
  if is_sequence_type(field_type):
647
864
  display_sequence_readonly(value, field_type, key)
648
865
  return
649
866
 
650
- # Handle nested models
651
867
  if is_dataclass_like(field_type):
652
868
  display_model_readonly(value, key)
653
869
  return
654
870
 
655
- # Handle Enum values
656
871
  if isinstance(value, Enum):
657
872
  st.text(str(value.name))
658
873
  return
659
874
 
660
- # Handle basic types
661
- if isinstance(value, bool):
662
- st.checkbox("", value=value, disabled=True, key=key)
663
- elif isinstance(value, int | float | Decimal | date | time | datetime):
664
- st.text(str(value))
665
- elif isinstance(value, str):
666
- if len(value) > 100: # Long text # noqa: PLR2004
667
- st.text_area("", value=value, disabled=True, height=100, key=key)
668
- else:
669
- st.text(value)
670
- else:
671
- # Default fallback for other types
672
- st.text(str(value))
875
+ match value:
876
+ case Enum() as enum_value:
877
+ st.text(str(enum_value.name))
878
+ case bool() as bool_value:
879
+ st.checkbox("", value=bool_value, disabled=True, key=key)
880
+ case int() | float() | Decimal() | date() | time() | datetime():
881
+ st.text(str(value))
882
+ case str() as str_value:
883
+ if len(str_value) > 100: # noqa: PLR2004
884
+ st.text_area("", value=str_value, disabled=True, height=100, key=key)
885
+ else:
886
+ st.text(str_value)
887
+ case _:
888
+ # Default fallback for other types
889
+ st.text(str(value))
673
890
 
674
891
 
675
892
  def display_sequence_readonly(value, field_type, key=None):
@@ -754,10 +971,7 @@ def render_model_form(model_or_instance, *, readonly: bool = False) -> Any:
754
971
  return instance # No changes in read-only mode
755
972
 
756
973
  result = {}
757
-
758
- # Group fields by category if metadata exists, otherwise use "General"
759
974
  field_groups: dict[str, Any] = {}
760
-
761
975
  for field in fieldz.fields(model_class):
762
976
  # Check if field has a category defined
763
977
  category = "General"
@@ -810,38 +1024,29 @@ if __name__ == "__main__":
810
1024
  class TestModel(BaseModel):
811
1025
  """Test model."""
812
1026
 
813
- status: int | str | bool = Field(
814
- 2, description="A field that can be either int, str, or bool"
815
- )
816
- optional_text: str | None = Field(None, description="Optional text field")
1027
+ status: int | str | bool = 2
1028
+ """A field that can be either int, str, or bool."""
817
1029
 
818
- # Lists with various types
819
- tags: list[str] = Field(default_factory=list, description="A list of string tags")
820
- numbers: list[int | float] = Field(
821
- default_factory=list, description="A list of numbers (int or float)"
822
- )
1030
+ optional_text: str | None = None
1031
+ """Optional text field."""
823
1032
 
824
- # Nested structures
825
- settings: list[SubModel] = Field(
826
- default_factory=list, description="A list of nested models"
827
- )
1033
+ tags: list[str] = Field(default_factory=list)
1034
+ """A list of string tags."""
828
1035
 
829
- # Combined with literals
830
- priorities: list[Literal["Low", "Medium", "High"]] = Field(
831
- default_factory=list, description="A list of priority levels"
832
- )
1036
+ numbers: list[int | float] = Field(default_factory=list)
1037
+ """A list of numbers (int or float)"""
1038
+
1039
+ settings: list[SubModel] = Field(default_factory=list)
1040
+ """A list of nested models"""
1041
+
1042
+ priorities: list[Literal["Low", "Medium", "High"]] = Field(default_factory=list)
1043
+ """A list of priority levels."""
833
1044
 
834
1045
  def demo():
835
1046
  st.title("Pydantic Form Demo")
836
-
837
- # Initialize or get model from session state
838
1047
  if "model" not in st.session_state:
839
1048
  st.session_state.model = TestModel(status=2, optional_text=None)
840
-
841
- # Render the complete form and update the model
842
1049
  st.session_state.model = render_model_form(TestModel)
843
-
844
- # Display current model state
845
1050
  with st.expander("Current Model State", expanded=True):
846
1051
  st.json(st.session_state.model.model_dump_json(indent=2))
847
1052
 
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ from collections.abc import Sequence
5
6
  from typing import Any, Literal, get_args, get_origin
6
7
 
7
8
  import fieldz
@@ -25,17 +26,21 @@ def is_union_type(annotation: Any) -> bool:
25
26
  )
26
27
 
27
28
 
29
+ def is_set_type(annotation: Any) -> bool:
30
+ """Check if the annotation represents a set type."""
31
+ if annotation is set:
32
+ return True
33
+ origin = get_origin(annotation)
34
+ return origin is set
35
+
36
+
28
37
  def is_sequence_type(annotation: Any) -> bool:
29
- """Check if a type annotation is a sequence type."""
38
+ """Check if an annotation represents a sequence type (except sets)."""
30
39
  origin = get_origin(annotation)
31
- if origin is None:
32
- return False
40
+ if origin in (list, tuple, Sequence):
41
+ return True
33
42
 
34
- try:
35
- return issubclass(origin, list | set | tuple)
36
- except TypeError:
37
- # Handle case where origin is not a class
38
- return False
43
+ return annotation in (list, tuple, Sequence)
39
44
 
40
45
 
41
46
  def get_with_default(obj: Any, field_name: str, field_info: Any = None) -> Any: # noqa: PLR0911
@@ -1,16 +0,0 @@
1
- __version__ = "0.2.1"
2
-
3
-
4
- from streambricks.widgets.model_widget import render_model_form, render_model_readonly
5
- from streambricks.widgets.multi_select import multiselect, MultiSelectItem
6
- from streambricks.widgets.model_selector import model_selector
7
- from streambricks.helpers import run
8
-
9
- __all__ = [
10
- "MultiSelectItem",
11
- "model_selector",
12
- "multiselect",
13
- "render_model_form",
14
- "render_model_readonly",
15
- "run",
16
- ]
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes