streambricks 0.2.16__tar.gz → 0.2.19__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 (41) hide show
  1. {streambricks-0.2.16 → streambricks-0.2.19}/.gitignore +1 -0
  2. {streambricks-0.2.16 → streambricks-0.2.19}/PKG-INFO +1 -1
  3. streambricks-0.2.19/docs/profile_widget.md +89 -0
  4. {streambricks-0.2.16 → streambricks-0.2.19}/src/streambricks/__init__.py +22 -1
  5. streambricks-0.2.19/src/streambricks/auth/__init__.py +16 -0
  6. streambricks-0.2.19/src/streambricks/auth/decorator.py +78 -0
  7. streambricks-0.2.19/src/streambricks/auth/helpers.py +123 -0
  8. streambricks-0.2.19/src/streambricks/auth/models.py +105 -0
  9. streambricks-0.2.19/src/streambricks/auth/profile_widget.py +196 -0
  10. streambricks-0.2.19/src/streambricks/sidebar.py +30 -0
  11. {streambricks-0.2.16 → streambricks-0.2.19}/.copier-answers.yml +0 -0
  12. {streambricks-0.2.16 → streambricks-0.2.19}/.github/FUNDING.yml +0 -0
  13. {streambricks-0.2.16 → streambricks-0.2.19}/.github/copilot-instructions.md +0 -0
  14. {streambricks-0.2.16 → streambricks-0.2.19}/.github/dependabot.yml +0 -0
  15. {streambricks-0.2.16 → streambricks-0.2.19}/.github/workflows/build.yml +0 -0
  16. {streambricks-0.2.16 → streambricks-0.2.19}/.github/workflows/documentation.yml +0 -0
  17. {streambricks-0.2.16 → streambricks-0.2.19}/.pre-commit-config.yaml +0 -0
  18. {streambricks-0.2.16 → streambricks-0.2.19}/LICENSE +0 -0
  19. {streambricks-0.2.16 → streambricks-0.2.19}/README.md +0 -0
  20. {streambricks-0.2.16 → streambricks-0.2.19}/docs/.empty +0 -0
  21. {streambricks-0.2.16 → streambricks-0.2.19}/duties.py +0 -0
  22. {streambricks-0.2.16 → streambricks-0.2.19}/mkdocs.yml +0 -0
  23. {streambricks-0.2.16 → streambricks-0.2.19}/overrides/_dummy.txt +0 -0
  24. {streambricks-0.2.16 → streambricks-0.2.19}/pyproject.toml +0 -0
  25. {streambricks-0.2.16 → streambricks-0.2.19}/src/streambricks/helpers.py +0 -0
  26. {streambricks-0.2.16 → streambricks-0.2.19}/src/streambricks/py.typed +0 -0
  27. {streambricks-0.2.16 → streambricks-0.2.19}/src/streambricks/state.py +0 -0
  28. {streambricks-0.2.16 → streambricks-0.2.19}/src/streambricks/widgets/__init__.py +0 -0
  29. {streambricks-0.2.16 → streambricks-0.2.19}/src/streambricks/widgets/bind_kwargs.py +0 -0
  30. {streambricks-0.2.16 → streambricks-0.2.19}/src/streambricks/widgets/image_capture.py +0 -0
  31. {streambricks-0.2.16 → streambricks-0.2.19}/src/streambricks/widgets/model_selector.py +0 -0
  32. {streambricks-0.2.16 → streambricks-0.2.19}/src/streambricks/widgets/model_widget/__init__.py +0 -0
  33. {streambricks-0.2.16 → streambricks-0.2.19}/src/streambricks/widgets/model_widget/field_metadata_renderers.py +0 -0
  34. {streambricks-0.2.16 → streambricks-0.2.19}/src/streambricks/widgets/model_widget/main.py +0 -0
  35. {streambricks-0.2.16 → streambricks-0.2.19}/src/streambricks/widgets/model_widget/type_renderers.py +0 -0
  36. {streambricks-0.2.16 → streambricks-0.2.19}/src/streambricks/widgets/multi_select.py +0 -0
  37. {streambricks-0.2.16 → streambricks-0.2.19}/src/streambricks/widgets/sequence.py +0 -0
  38. {streambricks-0.2.16 → streambricks-0.2.19}/src/streambricks/widgets/type_helpers.py +0 -0
  39. {streambricks-0.2.16 → streambricks-0.2.19}/tests/__init__.py +0 -0
  40. {streambricks-0.2.16 → streambricks-0.2.19}/tests/conftest.py +0 -0
  41. {streambricks-0.2.16 → streambricks-0.2.19}/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.16
3
+ Version: 0.2.19
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,89 @@
1
+ # Profile Widget
2
+
3
+ The profile widget provides a simple way to display user profile information in Streamlit apps. It shows a profile picture (if available) or generates an avatar with user initials and displays the user's name.
4
+
5
+ ## Features
6
+
7
+ - Uses Google profile picture if available
8
+ - Generates a colorful avatar with user initials if no picture is available
9
+ - Supports different sizes: small, medium, large
10
+ - Optional name display
11
+ - Custom name override option
12
+
13
+ ## Usage
14
+
15
+ ```python
16
+ import streamlit as st
17
+ from streambricks import profile_widget, google_login, microsoft_login
18
+
19
+ # Login with your preferred method
20
+ user = google_login("Login to see profile")
21
+ # OR
22
+ # user = microsoft_login("Login with Microsoft")
23
+
24
+ if user:
25
+ # Basic usage
26
+ profile_widget(user)
27
+
28
+ # Customize size
29
+ profile_widget(user, size="medium") # Options: "small", "medium", "large"
30
+
31
+ # Without name
32
+ profile_widget(user, show_name=False)
33
+
34
+ # Custom display name
35
+ profile_widget(user, display_name="Custom Name")
36
+ ```
37
+
38
+ ## API Reference
39
+
40
+ ```python
41
+ def profile_widget(
42
+ user: GoogleUser | MicrosoftUser | None = None,
43
+ display_name: str | None = None,
44
+ size: Literal["small", "medium", "large"] = "small",
45
+ show_name: bool = True,
46
+ key: str | None = None,
47
+ ) -> None:
48
+ ```
49
+
50
+ ### Parameters
51
+
52
+ - **user**: A `GoogleUser` or `MicrosoftUser` object obtained from login methods
53
+ - **display_name**: Optional custom name to display instead of the user's name
54
+ - **size**: Size of the avatar ("small", "medium", or "large")
55
+ - **show_name**: Whether to show the name beside the avatar
56
+ - **key**: Optional unique key for the Streamlit widget
57
+
58
+ ## Examples
59
+
60
+ ### Different Sizes
61
+
62
+ ```python
63
+ st.write("Available sizes:")
64
+ col1, col2, col3 = st.columns(3)
65
+
66
+ with col1:
67
+ st.caption("Small (default)")
68
+ profile_widget(user, size="small")
69
+
70
+ with col2:
71
+ st.caption("Medium")
72
+ profile_widget(user, size="medium")
73
+
74
+ with col3:
75
+ st.caption("Large")
76
+ profile_widget(user, size="large")
77
+ ```
78
+
79
+ ### Usage in Header
80
+
81
+ ```python
82
+ col1, col2 = st.columns([1, 5])
83
+
84
+ with col1:
85
+ profile_widget(user, show_name=False, size="medium")
86
+
87
+ with col2:
88
+ st.title("Dashboard")
89
+ ```
@@ -1,6 +1,17 @@
1
- __version__ = "0.2.16"
1
+ """StreamBricks components for Streamlit."""
2
2
 
3
+ __version__ = "0.2.19"
3
4
 
5
+
6
+ from streambricks.auth import (
7
+ GoogleUser,
8
+ MicrosoftUser,
9
+ get_current_user,
10
+ google_login,
11
+ microsoft_login,
12
+ profile_widget,
13
+ requires_login,
14
+ )
4
15
  from streambricks.widgets.model_widget import (
5
16
  render_model_form as model_edit,
6
17
  render_model_readonly as model_display,
@@ -14,16 +25,26 @@ from streambricks.widgets.model_selector import (
14
25
  from streambricks.helpers import run
15
26
  from streambricks.state import State
16
27
  from streambricks.widgets.bind_kwargs import bind_kwargs_as_widget
28
+ from streambricks.sidebar import hide_sidebar, set_sidebar_width
17
29
 
18
30
  __all__ = [
31
+ "GoogleUser",
32
+ "MicrosoftUser",
19
33
  "MultiSelectItem",
20
34
  "State",
21
35
  "bind_kwargs_as_widget",
36
+ "get_current_user",
37
+ "google_login",
38
+ "hide_sidebar",
22
39
  "image_capture",
23
40
  "llm_model_selector",
41
+ "microsoft_login",
24
42
  "model_display",
25
43
  "model_edit",
26
44
  "model_selector",
27
45
  "multiselect",
46
+ "profile_widget",
47
+ "requires_login",
28
48
  "run",
49
+ "set_sidebar_width",
29
50
  ]
@@ -0,0 +1,16 @@
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
+ from streambricks.auth.profile_widget import profile_widget
7
+
8
+ __all__ = [
9
+ "GoogleUser",
10
+ "MicrosoftUser",
11
+ "get_current_user",
12
+ "google_login",
13
+ "microsoft_login",
14
+ "profile_widget",
15
+ "requires_login",
16
+ ]
@@ -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,123 @@
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 getattr(st.experimental_user, "is_logged_in", False): # noqa: E501
21
+ if st.experimental_user and st.experimental_user.get("is_logged_in"):
22
+ return {**st.experimental_user}
23
+
24
+ return None
25
+
26
+
27
+ def google_login(
28
+ button_text: str = "Login with Google",
29
+ redirect_url: str | None = None,
30
+ key: str | None = None,
31
+ ) -> GoogleUser | None:
32
+ """Authenticate user with Google and return typed user object if successful.
33
+
34
+ Args:
35
+ button_text: Text to display on the login button
36
+ redirect_url: URL to redirect to after successful login
37
+ key: Streamlit widget key for the login button
38
+
39
+ Returns:
40
+ GoogleUser object if login successful, None otherwise
41
+ """
42
+ user_data = _get_user_data()
43
+ if user_data is not None:
44
+ # User is already logged in, return typed user object
45
+ return GoogleUser(**user_data) # pyright: ignore
46
+
47
+ # User not logged in, display login button
48
+ if st.button(button_text, key=key):
49
+ # The provider parameter should match what's configured in secrets.toml
50
+ st.login("google")
51
+
52
+ return None
53
+
54
+
55
+ def microsoft_login(
56
+ button_text: str = "Login with Microsoft",
57
+ redirect_url: str | None = None,
58
+ key: str | None = None,
59
+ ) -> MicrosoftUser | None:
60
+ """Authenticate user with Microsoft and return typed user object if successful.
61
+
62
+ Args:
63
+ button_text: Text to display on the login button
64
+ redirect_url: URL to redirect to after successful login
65
+ key: Streamlit widget key for the login button
66
+
67
+ Returns:
68
+ MicrosoftUser object if login successful, None otherwise
69
+ """
70
+ user_data = _get_user_data()
71
+ if user_data is not None:
72
+ # User is already logged in, return typed user object
73
+ return MicrosoftUser(**user_data) # pyright: ignore
74
+
75
+ # User not logged in, display login button
76
+ if st.button(button_text, key=key):
77
+ # The provider parameter should match what's configured in secrets.toml
78
+ st.login("microsoft")
79
+
80
+ return None
81
+
82
+
83
+ @overload
84
+ def get_current_user(user_class: type[T]) -> T: ...
85
+
86
+
87
+ @overload
88
+ def get_current_user() -> GoogleUser | MicrosoftUser | None: ...
89
+
90
+
91
+ def get_current_user(
92
+ user_class: type[T] | None = None,
93
+ ) -> T | GoogleUser | MicrosoftUser | None:
94
+ """Get the currently logged in user as a typed object.
95
+
96
+ Args:
97
+ user_class: The class to use for the user model (GoogleUser or MicrosoftUser).
98
+ If specified, errors will be raised if the data doesn't match.
99
+
100
+ Returns:
101
+ Typed user object if logged in and matching requested type,
102
+ None if no user_class specified and no user is logged in
103
+
104
+ Raises:
105
+ Various exceptions: If the user data doesn't match the requested model,
106
+ the original validation exceptions from Pydantic will be raised
107
+ """
108
+ user_data = _get_user_data()
109
+ if user_data is None:
110
+ if user_class is not None:
111
+ msg = "No user is currently logged in"
112
+ raise ValueError(msg)
113
+ return None
114
+
115
+ if user_class is not None:
116
+ return user_class(**user_data) # pyright: ignore
117
+ try:
118
+ return GoogleUser(**user_data) # pyright: ignore
119
+ except Exception: # noqa: BLE001
120
+ try:
121
+ return MicrosoftUser(**user_data) # pyright: ignore
122
+ except Exception: # noqa: BLE001
123
+ 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,196 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import functools
5
+ import hashlib
6
+ from io import BytesIO
7
+ from typing import Literal
8
+
9
+ from PIL import Image, ImageDraw, ImageFont
10
+ import streamlit as st
11
+
12
+ from streambricks.auth.models import GoogleUser, MicrosoftUser
13
+
14
+
15
+ @st.cache_data(ttl=3600, show_spinner=False)
16
+ def _generate_avatar_image(
17
+ initials: str,
18
+ bg_color: str | tuple[int, int, int] = "#1f77b4",
19
+ text_color: str | tuple[int, int, int] = "white",
20
+ size: int = 100,
21
+ ) -> Image.Image:
22
+ """Generate an avatar image with user initials.
23
+
24
+ Args:
25
+ initials: The text to display on the avatar (usually initials)
26
+ bg_color: Background color as hex string or RGB tuple
27
+ text_color: Text color as hex string or RGB tuple
28
+ size: Size of the image in pixels
29
+
30
+ Returns:
31
+ PIL Image with generated avatar
32
+ """
33
+ # Create a square image with the specified background color
34
+ img = Image.new("RGB", (size, size), bg_color)
35
+ draw = ImageDraw.Draw(img)
36
+
37
+ # Try to load a font, fall back to default if not available
38
+ font_size = int(size * 0.4) # 40% of image size
39
+ try:
40
+ font: ImageFont.FreeTypeFont | ImageFont.ImageFont = ImageFont.truetype(
41
+ "arial.ttf", font_size
42
+ )
43
+ except OSError:
44
+ font = ImageFont.load_default()
45
+
46
+ text_width, text_height = draw.textbbox((0, 0), initials, font=font)[2:]
47
+ x = (size - text_width) // 2
48
+ y = (size - text_height) // 2
49
+ draw.text((x, y), initials, fill=text_color, font=font)
50
+ mask = Image.new("L", (size, size), 0)
51
+ mask_draw = ImageDraw.Draw(mask)
52
+ mask_draw.ellipse((0, 0, size, size), fill=255)
53
+ img.putalpha(mask)
54
+
55
+ return img
56
+
57
+
58
+ def _get_initials(name: str) -> str:
59
+ """Extract initials from a name.
60
+
61
+ Args:
62
+ name: Full name of the user
63
+
64
+ Returns:
65
+ Initials (up to 2 characters)
66
+ """
67
+ parts = name.strip().split()
68
+ if not parts:
69
+ return "?"
70
+
71
+ if len(parts) == 1:
72
+ return parts[0][0].upper()
73
+
74
+ return (parts[0][0] + parts[-1][0]).upper()
75
+
76
+
77
+ @functools.lru_cache(maxsize=128)
78
+ def _get_color_from_string(s: str) -> str:
79
+ """Generate a consistent color from a string.
80
+
81
+ Args:
82
+ s: Input string (like user ID)
83
+
84
+ Returns:
85
+ Hex color code
86
+ """
87
+ # Use a hash function to get a reproducible integer from the string
88
+ hash_obj = hashlib.md5(s.encode())
89
+ hash_int = int.from_bytes(hash_obj.digest()[:4], "little")
90
+
91
+ # Select from a set of good UI colors (excluding very light ones)
92
+ colors = [
93
+ "#1f77b4", # blue
94
+ "#ff7f0e", # orange
95
+ "#2ca02c", # green
96
+ "#d62728", # red
97
+ "#9467bd", # purple
98
+ "#8c564b", # brown
99
+ "#e377c2", # pink
100
+ "#7f7f7f", # gray
101
+ "#bcbd22", # olive
102
+ "#17becf", # teal
103
+ ]
104
+
105
+ return colors[hash_int % len(colors)]
106
+
107
+
108
+ @st.cache_data(ttl=3600, show_spinner=False)
109
+ def _image_to_base64(img_hash: int, img: Image.Image) -> str:
110
+ """Convert a PIL Image to a base64 string.
111
+
112
+ Args:
113
+ img_hash: Hash of the image parameters for caching
114
+ img: PIL Image object
115
+
116
+ Returns:
117
+ Base64 encoded string of the image
118
+ """
119
+ # The img_hash parameter is only used for caching and isn't used in the function
120
+ buffer = BytesIO()
121
+ img.save(buffer, format="PNG")
122
+ return base64.b64encode(buffer.getvalue()).decode("utf-8")
123
+
124
+
125
+ def profile_widget(
126
+ user: GoogleUser | MicrosoftUser | None = None,
127
+ display_name: str | None = None,
128
+ size: Literal["small", "medium", "large"] = "small",
129
+ show_name: bool = True,
130
+ key: str | None = None,
131
+ ) -> None:
132
+ """Display a profile widget with user avatar and name.
133
+
134
+ Args:
135
+ user: GoogleUser or MicrosoftUser object
136
+ display_name: Optional name override to display instead of user's name
137
+ size: Size of the avatar image ("small", "medium", or "large")
138
+ show_name: Whether to show the name next to the avatar
139
+ key: Optional key for the Streamlit widget
140
+
141
+ Returns:
142
+ None
143
+ """
144
+ if user is None:
145
+ return
146
+
147
+ size_map = {"small": 32, "medium": 48, "large": 64}
148
+ img_size = size_map[size]
149
+ name = display_name or user.name
150
+ css = f"""
151
+ <style>
152
+ .profile-widget-{key if key else "default"} {{
153
+ display: flex;
154
+ align-items: center;
155
+ margin: 5px 0;
156
+ }}
157
+ .avatar-{key if key else "default"} {{
158
+ border-radius: 50%;
159
+ width: {img_size}px;
160
+ height: {img_size}px;
161
+ object-fit: cover;
162
+ }}
163
+ .profile-name-{key if key else "default"} {{
164
+ margin-left: 10px;
165
+ font-size: {int(img_size * 0.4)}px;
166
+ }}
167
+ </style>
168
+ """
169
+
170
+ img_src = ""
171
+ if isinstance(user, GoogleUser) and user.picture:
172
+ img_src = user.picture
173
+ else:
174
+ # Generate avatar with initials
175
+ initials = _get_initials(name)
176
+ color = _get_color_from_string(user.user_id)
177
+ # Double size for better quality
178
+ avatar_img = _generate_avatar_image(initials, color, size=img_size * 2)
179
+ # Create a hash of the parameters for caching the base64 conversion
180
+ img_hash = hash((initials, color, img_size))
181
+ img_src = f"data:image/png;base64,{_image_to_base64(img_hash, avatar_img)}"
182
+
183
+ # HTML for the widget
184
+ html = f"""
185
+ {css}
186
+ <div class="profile-widget-{key if key else "default"}">
187
+ <img src="{img_src}" class="avatar-{key if key else "default"}" alt="User Avatar">
188
+ {
189
+ f'<span class="profile-name-{key if key else "default"}">{name}</span>'
190
+ if show_name
191
+ else ""
192
+ }
193
+ </div>
194
+ """
195
+
196
+ st.markdown(html, unsafe_allow_html=True)
@@ -0,0 +1,30 @@
1
+ import streamlit as st
2
+
3
+
4
+ HIDE_SIDEBAR = """\
5
+ <style>
6
+ [data-testid="stSidebar"][aria-expanded="true"] {display: none;}
7
+ [data-testid="stSidebar"][aria-expanded="false"] {display: none;}
8
+ </style>
9
+ """
10
+
11
+
12
+ def set_sidebar_width(width: int):
13
+ st.markdown(
14
+ f"""\
15
+ <style>
16
+ [data-testid="stSidebar"][aria-expanded="true"] > div:first-child {{
17
+ width: {width}px;
18
+ }}
19
+ [data-testid="stSidebar"][aria-expanded="false"] > div:first-child {{
20
+ width: {width}px;
21
+ margin-left: -{width}px;
22
+ }}
23
+ </style>
24
+ """,
25
+ unsafe_allow_html=True,
26
+ )
27
+
28
+
29
+ def hide_sidebar():
30
+ st.markdown(HIDE_SIDEBAR, unsafe_allow_html=True)
File without changes
File without changes
File without changes
File without changes
File without changes