streambricks 0.0.1__py3-none-any.whl
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.
- streambricks/__init__.py +8 -0
- streambricks/helpers.py +48 -0
- streambricks/py.typed +0 -0
- streambricks/widgets/__init__.py +6 -0
- streambricks/widgets/model_widget.py +1123 -0
- streambricks/widgets/multi_select.py +91 -0
- streambricks-0.0.1.dist-info/METADATA +82 -0
- streambricks-0.0.1.dist-info/RECORD +10 -0
- streambricks-0.0.1.dist-info/WHEEL +4 -0
- streambricks-0.0.1.dist-info/licenses/LICENSE +22 -0
|
@@ -0,0 +1,1123 @@
|
|
|
1
|
+
"""Primitive type handlers for Pydantic form fields."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, Sequence
|
|
6
|
+
import contextlib
|
|
7
|
+
from datetime import date, datetime, time
|
|
8
|
+
from decimal import Decimal
|
|
9
|
+
from enum import Enum
|
|
10
|
+
from typing import TYPE_CHECKING, Any, Literal, TypeVar, get_args, get_origin, overload
|
|
11
|
+
|
|
12
|
+
import fieldz
|
|
13
|
+
import streamlit as st
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from pydantic import BaseModel
|
|
18
|
+
|
|
19
|
+
T = TypeVar("T")
|
|
20
|
+
WidgetFunc = Callable[..., T]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _get_with_default(obj: Any, field_name: str, field_info: Any = None) -> Any: # noqa: PLR0911
|
|
24
|
+
"""Get field value with appropriate default if it's missing."""
|
|
25
|
+
# Get the raw value
|
|
26
|
+
value = getattr(obj, field_name, None)
|
|
27
|
+
|
|
28
|
+
# If value isn't MISSING, return it as is
|
|
29
|
+
if value != "MISSING":
|
|
30
|
+
return value
|
|
31
|
+
|
|
32
|
+
# If we don't have field info, get it
|
|
33
|
+
if field_info is None:
|
|
34
|
+
for field in fieldz.fields(obj.__class__):
|
|
35
|
+
if field.name == field_name:
|
|
36
|
+
field_info = field
|
|
37
|
+
break
|
|
38
|
+
|
|
39
|
+
# If we have field info, use it to determine appropriate default
|
|
40
|
+
if field_info is not None:
|
|
41
|
+
field_type = field_info.type
|
|
42
|
+
|
|
43
|
+
# Handle Union types
|
|
44
|
+
if is_union_type(field_type):
|
|
45
|
+
types = [t for t in get_args(field_type) if t is not type(None)]
|
|
46
|
+
if int in types:
|
|
47
|
+
return 0
|
|
48
|
+
if float in types:
|
|
49
|
+
return 0.0
|
|
50
|
+
if str in types:
|
|
51
|
+
return ""
|
|
52
|
+
if bool in types:
|
|
53
|
+
return False
|
|
54
|
+
if types and isinstance(types[0], type):
|
|
55
|
+
if issubclass(types[0], int):
|
|
56
|
+
return 0
|
|
57
|
+
if issubclass(types[0], float):
|
|
58
|
+
return 0.0
|
|
59
|
+
if issubclass(types[0], str):
|
|
60
|
+
return ""
|
|
61
|
+
if issubclass(types[0], bool):
|
|
62
|
+
return False
|
|
63
|
+
|
|
64
|
+
# Handle basic types
|
|
65
|
+
if isinstance(field_type, type):
|
|
66
|
+
if issubclass(field_type, int):
|
|
67
|
+
return 0
|
|
68
|
+
if issubclass(field_type, float):
|
|
69
|
+
return 0.0
|
|
70
|
+
if issubclass(field_type, str):
|
|
71
|
+
return ""
|
|
72
|
+
if issubclass(field_type, bool):
|
|
73
|
+
return False
|
|
74
|
+
if (
|
|
75
|
+
issubclass(field_type, list)
|
|
76
|
+
or issubclass(field_type, set)
|
|
77
|
+
or issubclass(field_type, tuple)
|
|
78
|
+
):
|
|
79
|
+
return []
|
|
80
|
+
|
|
81
|
+
# Default fallback for unknown types
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def render_str_field(
|
|
86
|
+
*,
|
|
87
|
+
key: str,
|
|
88
|
+
value: str | None = None,
|
|
89
|
+
label: str | None = None,
|
|
90
|
+
disabled: bool = False,
|
|
91
|
+
**field_info: Any,
|
|
92
|
+
) -> str:
|
|
93
|
+
"""Render a string field using appropriate Streamlit widget."""
|
|
94
|
+
max_length = field_info.get("max_length", 0)
|
|
95
|
+
multiple_lines = field_info.get("multiple_lines", False)
|
|
96
|
+
|
|
97
|
+
if max_length > 100 or multiple_lines: # noqa: PLR2004
|
|
98
|
+
return st.text_area(
|
|
99
|
+
label=label or key,
|
|
100
|
+
value=value or "",
|
|
101
|
+
disabled=disabled,
|
|
102
|
+
key=key,
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
return st.text_input(
|
|
106
|
+
label=label or key,
|
|
107
|
+
value=value or "",
|
|
108
|
+
disabled=disabled,
|
|
109
|
+
key=key,
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def render_int_field(
|
|
114
|
+
*,
|
|
115
|
+
key: str,
|
|
116
|
+
value: int | None = None,
|
|
117
|
+
label: str | None = None,
|
|
118
|
+
disabled: bool = False,
|
|
119
|
+
**field_info: Any,
|
|
120
|
+
) -> int:
|
|
121
|
+
"""Render an integer field using Streamlit number_input."""
|
|
122
|
+
# Set default value
|
|
123
|
+
safe_value = int(value) if value is not None else 0
|
|
124
|
+
|
|
125
|
+
# Extract constraints, ensuring they're integers
|
|
126
|
+
min_value = field_info.get("ge") or field_info.get("gt")
|
|
127
|
+
min_value = int(min_value) if min_value is not None else None
|
|
128
|
+
|
|
129
|
+
max_value = field_info.get("le") or field_info.get("lt")
|
|
130
|
+
max_value = int(max_value) if max_value is not None else None
|
|
131
|
+
|
|
132
|
+
step = field_info.get("multiple_of")
|
|
133
|
+
step = int(step) if step is not None else 1
|
|
134
|
+
|
|
135
|
+
result = st.number_input(
|
|
136
|
+
label=label or key,
|
|
137
|
+
value=safe_value,
|
|
138
|
+
min_value=min_value,
|
|
139
|
+
max_value=max_value,
|
|
140
|
+
step=step,
|
|
141
|
+
disabled=disabled,
|
|
142
|
+
key=key,
|
|
143
|
+
format="%d", # Use integer format
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
return int(result)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def render_float_field(
|
|
150
|
+
*,
|
|
151
|
+
key: str,
|
|
152
|
+
value: float | Decimal | None = None,
|
|
153
|
+
label: str | None = None,
|
|
154
|
+
disabled: bool = False,
|
|
155
|
+
**field_info: Any,
|
|
156
|
+
) -> float | Decimal:
|
|
157
|
+
"""Render a float or Decimal field using Streamlit number_input."""
|
|
158
|
+
# Determine if we're dealing with a Decimal
|
|
159
|
+
field_type = field_info.get("type")
|
|
160
|
+
is_decimal = field_type is Decimal
|
|
161
|
+
|
|
162
|
+
# Convert to float for Streamlit compatibility
|
|
163
|
+
safe_value = float(value) if value is not None else 0.0
|
|
164
|
+
|
|
165
|
+
# Extract constraints, ensuring they're floats
|
|
166
|
+
min_value = field_info.get("ge") or field_info.get("gt")
|
|
167
|
+
min_value = float(min_value) if min_value is not None else None
|
|
168
|
+
|
|
169
|
+
max_value = field_info.get("le") or field_info.get("lt")
|
|
170
|
+
max_value = float(max_value) if max_value is not None else None
|
|
171
|
+
|
|
172
|
+
step = field_info.get("multiple_of")
|
|
173
|
+
step = float(step) if step is not None else 0.01
|
|
174
|
+
|
|
175
|
+
result = st.number_input(
|
|
176
|
+
label=label or key,
|
|
177
|
+
value=safe_value,
|
|
178
|
+
min_value=min_value,
|
|
179
|
+
max_value=max_value,
|
|
180
|
+
step=step,
|
|
181
|
+
disabled=disabled,
|
|
182
|
+
key=key,
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
# Convert back to Decimal if needed
|
|
186
|
+
if is_decimal:
|
|
187
|
+
return Decimal(str(result))
|
|
188
|
+
|
|
189
|
+
return result
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def render_bool_field(
|
|
193
|
+
*,
|
|
194
|
+
key: str,
|
|
195
|
+
value: bool | None = None,
|
|
196
|
+
label: str | None = None,
|
|
197
|
+
disabled: bool = False,
|
|
198
|
+
**field_info: Any,
|
|
199
|
+
) -> bool:
|
|
200
|
+
"""Render a boolean field using appropriate Streamlit widget."""
|
|
201
|
+
return st.checkbox(
|
|
202
|
+
label=label or key,
|
|
203
|
+
value=value if value is not None else False,
|
|
204
|
+
disabled=disabled,
|
|
205
|
+
key=key,
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def render_date_field(
|
|
210
|
+
*,
|
|
211
|
+
key: str,
|
|
212
|
+
value: date | None = None,
|
|
213
|
+
label: str | None = None,
|
|
214
|
+
disabled: bool = False,
|
|
215
|
+
**field_info: Any,
|
|
216
|
+
) -> date:
|
|
217
|
+
"""Render a date field using appropriate Streamlit widget."""
|
|
218
|
+
return st.date_input(
|
|
219
|
+
label=label or key,
|
|
220
|
+
value=value or date.today(),
|
|
221
|
+
disabled=disabled,
|
|
222
|
+
key=key,
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def render_time_field(
|
|
227
|
+
*,
|
|
228
|
+
key: str,
|
|
229
|
+
value: time | None = None,
|
|
230
|
+
label: str | None = None,
|
|
231
|
+
disabled: bool = False,
|
|
232
|
+
**field_info: Any,
|
|
233
|
+
) -> time:
|
|
234
|
+
"""Render a time field using appropriate Streamlit widget."""
|
|
235
|
+
return st.time_input(
|
|
236
|
+
label=label or key,
|
|
237
|
+
value=value or datetime.now().time(),
|
|
238
|
+
disabled=disabled,
|
|
239
|
+
key=key,
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def render_enum_field(
|
|
244
|
+
*,
|
|
245
|
+
key: str,
|
|
246
|
+
value: Enum | None = None,
|
|
247
|
+
label: str | None = None,
|
|
248
|
+
disabled: bool = False,
|
|
249
|
+
**field_info: Any,
|
|
250
|
+
) -> Enum:
|
|
251
|
+
"""Render an enum field using appropriate Streamlit widget."""
|
|
252
|
+
enum_class = field_info.get("enum_class") or field_info.get("type")
|
|
253
|
+
|
|
254
|
+
# Handle the case where enum_class might not be valid
|
|
255
|
+
if enum_class is None or not issubclass(enum_class, Enum):
|
|
256
|
+
error_msg = f"Invalid enum class for field {key}"
|
|
257
|
+
raise TypeError(error_msg)
|
|
258
|
+
|
|
259
|
+
# Get enum options - every Enum class is iterable over its members
|
|
260
|
+
options = list(enum_class.__members__.values())
|
|
261
|
+
|
|
262
|
+
if not options:
|
|
263
|
+
return None # type: ignore
|
|
264
|
+
|
|
265
|
+
# Find index of current value in options
|
|
266
|
+
index = 0
|
|
267
|
+
if value is not None:
|
|
268
|
+
with contextlib.suppress(ValueError):
|
|
269
|
+
index = options.index(value)
|
|
270
|
+
|
|
271
|
+
return st.selectbox(
|
|
272
|
+
label=label or key,
|
|
273
|
+
options=options,
|
|
274
|
+
index=index,
|
|
275
|
+
disabled=disabled,
|
|
276
|
+
key=key,
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def render_literal_field(
|
|
281
|
+
*,
|
|
282
|
+
key: str,
|
|
283
|
+
value: Any = None,
|
|
284
|
+
label: str | None = None,
|
|
285
|
+
disabled: bool = False,
|
|
286
|
+
**field_info: Any,
|
|
287
|
+
) -> Any:
|
|
288
|
+
"""Render a Literal field using appropriate Streamlit widget."""
|
|
289
|
+
annotation = field_info.get("type") or field_info.get("annotation")
|
|
290
|
+
options = get_args(annotation)
|
|
291
|
+
|
|
292
|
+
# No need for radio if only one option
|
|
293
|
+
if len(options) == 1:
|
|
294
|
+
return options[0]
|
|
295
|
+
|
|
296
|
+
# Use radio for boolean literals
|
|
297
|
+
if all(isinstance(opt, bool) for opt in options):
|
|
298
|
+
index = options.index(value) if value in options else 0
|
|
299
|
+
return st.radio(
|
|
300
|
+
label=label or key,
|
|
301
|
+
options=options,
|
|
302
|
+
index=index,
|
|
303
|
+
disabled=disabled,
|
|
304
|
+
key=key,
|
|
305
|
+
horizontal=True,
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
# Use selectbox for other literals
|
|
309
|
+
index = options.index(value) if value in options else 0
|
|
310
|
+
return st.selectbox(
|
|
311
|
+
label=label or key,
|
|
312
|
+
options=options,
|
|
313
|
+
index=index,
|
|
314
|
+
disabled=disabled,
|
|
315
|
+
key=key,
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def is_literal_type(annotation: Any) -> bool:
|
|
320
|
+
"""Check if a type annotation is a Literal type."""
|
|
321
|
+
# Check directly against the origin or special attribute
|
|
322
|
+
return (
|
|
323
|
+
get_origin(annotation) is Literal
|
|
324
|
+
or getattr(annotation, "__origin__", None) is Literal
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def is_union_type(annotation: Any) -> bool:
|
|
329
|
+
"""Check if a type annotation is a Union type."""
|
|
330
|
+
origin = get_origin(annotation)
|
|
331
|
+
# Check if it's Union or Optional (which is Union[T, None])
|
|
332
|
+
return origin is not None and (
|
|
333
|
+
origin.__name__ == "Union" if hasattr(origin, "__name__") else False
|
|
334
|
+
)
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def is_sequence_type(annotation: Any) -> bool:
|
|
338
|
+
"""Check if a type annotation is a sequence type."""
|
|
339
|
+
origin = get_origin(annotation)
|
|
340
|
+
if origin is None:
|
|
341
|
+
return False
|
|
342
|
+
|
|
343
|
+
try:
|
|
344
|
+
return issubclass(origin, list | set | tuple)
|
|
345
|
+
except TypeError:
|
|
346
|
+
# Handle case where origin is not a class
|
|
347
|
+
return False
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def render_union_field( # noqa: PLR0911
|
|
351
|
+
*,
|
|
352
|
+
key: str,
|
|
353
|
+
value: Any = None,
|
|
354
|
+
label: str | None = None,
|
|
355
|
+
disabled: bool = False,
|
|
356
|
+
**field_info: Any,
|
|
357
|
+
) -> Any:
|
|
358
|
+
"""Render a field that can accept multiple types."""
|
|
359
|
+
annotation = field_info.get("type") or field_info.get("annotation")
|
|
360
|
+
possible_types = get_args(annotation)
|
|
361
|
+
|
|
362
|
+
# Create type selector
|
|
363
|
+
type_key = f"{key}_type"
|
|
364
|
+
type_names = [
|
|
365
|
+
t.__name__ if hasattr(t, "__name__") else str(t) for t in possible_types
|
|
366
|
+
]
|
|
367
|
+
|
|
368
|
+
selected_type_name = st.selectbox(
|
|
369
|
+
f"Type for {label or key}",
|
|
370
|
+
options=type_names,
|
|
371
|
+
key=type_key,
|
|
372
|
+
disabled=disabled,
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
# Find selected type
|
|
376
|
+
selected_type_index = type_names.index(selected_type_name)
|
|
377
|
+
selected_type = possible_types[selected_type_index]
|
|
378
|
+
|
|
379
|
+
# Create field for selected type
|
|
380
|
+
field_key = f"{key}_value"
|
|
381
|
+
modified_field_info = field_info.copy()
|
|
382
|
+
modified_field_info["type"] = selected_type
|
|
383
|
+
|
|
384
|
+
# Only pass value if it matches the selected type or can be converted
|
|
385
|
+
typed_value: Any = None
|
|
386
|
+
if value is not None:
|
|
387
|
+
# Try to convert the value to the selected type
|
|
388
|
+
try:
|
|
389
|
+
if selected_type is int and isinstance(value, int | float):
|
|
390
|
+
typed_value = int(value)
|
|
391
|
+
elif selected_type is float and isinstance(value, int | float):
|
|
392
|
+
typed_value = float(value)
|
|
393
|
+
elif selected_type is str:
|
|
394
|
+
typed_value = str(value)
|
|
395
|
+
elif selected_type is bool:
|
|
396
|
+
# Handle conversion to bool (0/False, anything else/True)
|
|
397
|
+
if isinstance(value, int | float):
|
|
398
|
+
typed_value = bool(value)
|
|
399
|
+
else:
|
|
400
|
+
typed_value = bool(value)
|
|
401
|
+
elif isinstance(value, selected_type):
|
|
402
|
+
typed_value = value
|
|
403
|
+
except (ValueError, TypeError):
|
|
404
|
+
# If conversion fails, start with a blank/default value
|
|
405
|
+
pass
|
|
406
|
+
|
|
407
|
+
renderer = get_field_renderer(modified_field_info)
|
|
408
|
+
result = renderer(
|
|
409
|
+
key=field_key,
|
|
410
|
+
value=typed_value,
|
|
411
|
+
label=label,
|
|
412
|
+
disabled=disabled,
|
|
413
|
+
**modified_field_info,
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
# Ensure the result is of the correct type
|
|
417
|
+
try:
|
|
418
|
+
if selected_type is int and not isinstance(result, int):
|
|
419
|
+
return int(result)
|
|
420
|
+
if selected_type is float and not isinstance(result, float):
|
|
421
|
+
return float(result)
|
|
422
|
+
if selected_type is str and not isinstance(result, str):
|
|
423
|
+
return str(result)
|
|
424
|
+
if selected_type is bool and not isinstance(result, bool):
|
|
425
|
+
return bool(result)
|
|
426
|
+
except (ValueError, TypeError) as e:
|
|
427
|
+
error_msg = f"Cannot convert {result} to {selected_type.__name__}: {e!s}"
|
|
428
|
+
st.error(error_msg)
|
|
429
|
+
# Return a default value for the selected type
|
|
430
|
+
if selected_type is int:
|
|
431
|
+
return 0
|
|
432
|
+
if selected_type is float:
|
|
433
|
+
return 0.0
|
|
434
|
+
if selected_type is str:
|
|
435
|
+
return ""
|
|
436
|
+
if selected_type is bool:
|
|
437
|
+
return False
|
|
438
|
+
return None
|
|
439
|
+
else:
|
|
440
|
+
return result
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def create_default_instance(model_class: type) -> Any:
|
|
444
|
+
"""Create a default instance of a model with default values for required fields."""
|
|
445
|
+
# Create an empty dict to collect required values
|
|
446
|
+
default_values = {}
|
|
447
|
+
|
|
448
|
+
# Get all fields
|
|
449
|
+
for field in fieldz.fields(model_class):
|
|
450
|
+
field_name = field.name
|
|
451
|
+
|
|
452
|
+
# Check if the field already has a default value
|
|
453
|
+
has_default = False
|
|
454
|
+
if hasattr(field, "default") and field.default != "MISSING":
|
|
455
|
+
# Use the field's default value
|
|
456
|
+
default_values[field_name] = field.default
|
|
457
|
+
has_default = True
|
|
458
|
+
elif hasattr(field, "default_factory") and field.default_factory != "MISSING":
|
|
459
|
+
try:
|
|
460
|
+
# Use the field's default factory
|
|
461
|
+
default_values[field_name] = field.default_factory() # pyright: ignore
|
|
462
|
+
has_default = True
|
|
463
|
+
except Exception: # noqa: BLE001
|
|
464
|
+
# If default_factory fails, fall back to type-based defaults
|
|
465
|
+
pass
|
|
466
|
+
|
|
467
|
+
# If the field doesn't have a default, create one based on type
|
|
468
|
+
if not has_default:
|
|
469
|
+
field_type = field.type
|
|
470
|
+
|
|
471
|
+
# Handle union types
|
|
472
|
+
if is_union_type(field_type):
|
|
473
|
+
types = [t for t in get_args(field_type) if t is not type(None)]
|
|
474
|
+
if int in types:
|
|
475
|
+
default_values[field_name] = 0
|
|
476
|
+
elif float in types:
|
|
477
|
+
default_values[field_name] = 0.0
|
|
478
|
+
elif str in types:
|
|
479
|
+
default_values[field_name] = ""
|
|
480
|
+
elif bool in types:
|
|
481
|
+
default_values[field_name] = False
|
|
482
|
+
continue
|
|
483
|
+
|
|
484
|
+
# Set type-appropriate default values based on Python type
|
|
485
|
+
if isinstance(field_type, type):
|
|
486
|
+
if issubclass(field_type, str):
|
|
487
|
+
default_values[field_name] = ""
|
|
488
|
+
elif issubclass(field_type, int):
|
|
489
|
+
default_values[field_name] = 0
|
|
490
|
+
elif issubclass(field_type, float):
|
|
491
|
+
default_values[field_name] = 0.0
|
|
492
|
+
elif issubclass(field_type, bool):
|
|
493
|
+
default_values[field_name] = False
|
|
494
|
+
elif is_dataclass_like(field_type):
|
|
495
|
+
# For nested models, recursively create default instances
|
|
496
|
+
default_values[field_name] = create_default_instance(field_type)
|
|
497
|
+
|
|
498
|
+
# Create and return the instance with the default values
|
|
499
|
+
try:
|
|
500
|
+
return model_class(**default_values)
|
|
501
|
+
except Exception as e: # noqa: BLE001
|
|
502
|
+
error_msg = f"Error creating default instance: {e}"
|
|
503
|
+
st.error(error_msg)
|
|
504
|
+
return None
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def render_sequence_field(
|
|
508
|
+
*,
|
|
509
|
+
key: str,
|
|
510
|
+
value: Sequence[Any] | None = None,
|
|
511
|
+
label: str | None = None,
|
|
512
|
+
disabled: bool = False,
|
|
513
|
+
**field_info: Any,
|
|
514
|
+
) -> list[Any]:
|
|
515
|
+
"""Render a field for sequence types (list, tuple, set)."""
|
|
516
|
+
annotation = field_info.get("type") or field_info.get("annotation")
|
|
517
|
+
|
|
518
|
+
# Create unique state keys for this field
|
|
519
|
+
add_item_key = f"{key}_add_item"
|
|
520
|
+
items_key = f"{key}_items"
|
|
521
|
+
|
|
522
|
+
# Initialize session state for this field
|
|
523
|
+
if items_key not in st.session_state:
|
|
524
|
+
st.session_state[items_key] = list(value) if value is not None else []
|
|
525
|
+
|
|
526
|
+
# Extract item type from sequence annotation
|
|
527
|
+
try:
|
|
528
|
+
item_type = get_args(annotation)[0] # Get type of sequence items
|
|
529
|
+
except (IndexError, TypeError):
|
|
530
|
+
item_type = Any
|
|
531
|
+
|
|
532
|
+
# Check if we're already inside an expander
|
|
533
|
+
inside_expander = field_info.get("inside_expander", False)
|
|
534
|
+
|
|
535
|
+
# Create container for sequence elements
|
|
536
|
+
if not inside_expander:
|
|
537
|
+
st.markdown(f"**{label or key}**")
|
|
538
|
+
with st.container():
|
|
539
|
+
# Add new item button
|
|
540
|
+
if st.button("Add Item", key=add_item_key, disabled=disabled):
|
|
541
|
+
add_new_item(st.session_state[items_key], item_type)
|
|
542
|
+
|
|
543
|
+
# Render items
|
|
544
|
+
render_sequence_items(
|
|
545
|
+
st.session_state[items_key],
|
|
546
|
+
item_type,
|
|
547
|
+
key,
|
|
548
|
+
items_key,
|
|
549
|
+
disabled,
|
|
550
|
+
field_info,
|
|
551
|
+
)
|
|
552
|
+
else:
|
|
553
|
+
# Already inside an expander, use simple container
|
|
554
|
+
# Add new item button
|
|
555
|
+
if st.button("Add Item", key=add_item_key, disabled=disabled):
|
|
556
|
+
add_new_item(st.session_state[items_key], item_type)
|
|
557
|
+
|
|
558
|
+
# Render items
|
|
559
|
+
render_sequence_items(
|
|
560
|
+
st.session_state[items_key], item_type, key, items_key, disabled, field_info
|
|
561
|
+
)
|
|
562
|
+
|
|
563
|
+
# Return the current items
|
|
564
|
+
return st.session_state[items_key]
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def add_new_item(items_list: list, item_type: Any) -> None:
|
|
568
|
+
"""Add a new item to a list based on its type."""
|
|
569
|
+
if is_dataclass_like(item_type):
|
|
570
|
+
# For dataclass-like types, create a default instance
|
|
571
|
+
new_item = create_default_instance(item_type)
|
|
572
|
+
if new_item is not None:
|
|
573
|
+
items_list.append(new_item)
|
|
574
|
+
# For basic types, add appropriate default values
|
|
575
|
+
elif item_type is str:
|
|
576
|
+
items_list.append("")
|
|
577
|
+
elif item_type is int:
|
|
578
|
+
items_list.append(0)
|
|
579
|
+
elif item_type is float:
|
|
580
|
+
items_list.append(0.0)
|
|
581
|
+
elif item_type is bool:
|
|
582
|
+
items_list.append(False)
|
|
583
|
+
elif is_union_type(item_type):
|
|
584
|
+
# For union types, use the first non-None type
|
|
585
|
+
types = [t for t in get_args(item_type) if t is not type(None)]
|
|
586
|
+
if int in types:
|
|
587
|
+
items_list.append(0)
|
|
588
|
+
elif float in types:
|
|
589
|
+
items_list.append(0.0)
|
|
590
|
+
elif str in types:
|
|
591
|
+
items_list.append("")
|
|
592
|
+
elif bool in types:
|
|
593
|
+
items_list.append(False)
|
|
594
|
+
else:
|
|
595
|
+
items_list.append(None)
|
|
596
|
+
else:
|
|
597
|
+
# For unknown types, add None
|
|
598
|
+
items_list.append(None)
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
def render_sequence_items(
|
|
602
|
+
items: list,
|
|
603
|
+
item_type: Any,
|
|
604
|
+
key: str,
|
|
605
|
+
items_key: str,
|
|
606
|
+
disabled: bool,
|
|
607
|
+
field_info: dict,
|
|
608
|
+
) -> None:
|
|
609
|
+
"""Render items in a sequence with delete buttons."""
|
|
610
|
+
# Prepare item field info
|
|
611
|
+
item_info = field_info.copy()
|
|
612
|
+
item_info["type"] = item_type
|
|
613
|
+
item_info["inside_expander"] = True # Mark as inside a container
|
|
614
|
+
|
|
615
|
+
# Try to get renderer for item type
|
|
616
|
+
try:
|
|
617
|
+
renderer = get_field_renderer(item_info)
|
|
618
|
+
|
|
619
|
+
# Track which items to delete
|
|
620
|
+
items_to_delete = []
|
|
621
|
+
|
|
622
|
+
# Render each item with a delete button
|
|
623
|
+
for i, item in enumerate(items):
|
|
624
|
+
st.divider()
|
|
625
|
+
st.markdown(f"**Item {i + 1}**")
|
|
626
|
+
|
|
627
|
+
# Render the item
|
|
628
|
+
items[i] = 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
|
+
# Delete button for this item
|
|
637
|
+
delete_key = f"{key}_delete_{i}"
|
|
638
|
+
if st.button("Delete Item", key=delete_key, disabled=disabled):
|
|
639
|
+
items_to_delete.append(i)
|
|
640
|
+
|
|
641
|
+
# Process deletions (in reverse order to avoid index shifting)
|
|
642
|
+
if items_to_delete:
|
|
643
|
+
for idx in sorted(items_to_delete, reverse=True):
|
|
644
|
+
if 0 <= idx < len(items):
|
|
645
|
+
items.pop(idx)
|
|
646
|
+
st.rerun() # Force rerun after deletion
|
|
647
|
+
|
|
648
|
+
except Exception as e: # noqa: BLE001
|
|
649
|
+
st.error(f"Error rendering sequence items: {e!s}")
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
def render_model_instance_field(
|
|
653
|
+
*,
|
|
654
|
+
key: str,
|
|
655
|
+
value: Any = None,
|
|
656
|
+
label: str | None = None,
|
|
657
|
+
disabled: bool = False,
|
|
658
|
+
**field_info: Any,
|
|
659
|
+
) -> Any:
|
|
660
|
+
"""Render a nested model instance field."""
|
|
661
|
+
model_class = field_info.get("type")
|
|
662
|
+
if model_class is None:
|
|
663
|
+
error_msg = f"Model class not provided for field {key}"
|
|
664
|
+
raise ValueError(error_msg)
|
|
665
|
+
|
|
666
|
+
# Initialize value if none
|
|
667
|
+
if value is None:
|
|
668
|
+
value = create_default_instance(model_class)
|
|
669
|
+
if value is None: # If creation failed
|
|
670
|
+
try:
|
|
671
|
+
value = model_class()
|
|
672
|
+
except Exception as e: # noqa: BLE001
|
|
673
|
+
error_msg = f"Failed to create instance of {model_class.__name__}: {e!s}"
|
|
674
|
+
st.error(error_msg)
|
|
675
|
+
return None
|
|
676
|
+
|
|
677
|
+
# Check if we're already inside an expander
|
|
678
|
+
inside_expander = field_info.get("inside_expander", False)
|
|
679
|
+
|
|
680
|
+
# If needed, wrap in a container (not an expander)
|
|
681
|
+
if not inside_expander:
|
|
682
|
+
st.markdown(f"**{label or key}**")
|
|
683
|
+
container = st.container()
|
|
684
|
+
container.divider()
|
|
685
|
+
else:
|
|
686
|
+
container = st
|
|
687
|
+
|
|
688
|
+
# Render each field of the nested model
|
|
689
|
+
updated_value = {}
|
|
690
|
+
|
|
691
|
+
try:
|
|
692
|
+
for field in fieldz.fields(model_class):
|
|
693
|
+
field_name = field.name
|
|
694
|
+
|
|
695
|
+
# Get field value and handle 'MISSING' with type-appropriate defaults
|
|
696
|
+
field_value = _get_with_default(value, field_name, field)
|
|
697
|
+
|
|
698
|
+
# Add label for the field
|
|
699
|
+
container.caption(f"{field_name.replace('_', ' ').title()}")
|
|
700
|
+
|
|
701
|
+
# Get field description if available
|
|
702
|
+
if hasattr(field, "metadata") and "description" in field.metadata:
|
|
703
|
+
description = field.metadata["description"]
|
|
704
|
+
container.markdown(
|
|
705
|
+
f"<small>{description}</small>", unsafe_allow_html=True
|
|
706
|
+
)
|
|
707
|
+
elif hasattr(field, "native_field") and hasattr(
|
|
708
|
+
field.native_field, "description"
|
|
709
|
+
):
|
|
710
|
+
description = field.native_field.description # type: ignore
|
|
711
|
+
container.markdown(
|
|
712
|
+
f"<small>{description}</small>", unsafe_allow_html=True
|
|
713
|
+
)
|
|
714
|
+
|
|
715
|
+
# Extract field info
|
|
716
|
+
nested_field_info = {
|
|
717
|
+
"name": field_name,
|
|
718
|
+
"type": field.type,
|
|
719
|
+
"inside_expander": True, # Mark as inside a container
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
# Extract additional properties
|
|
723
|
+
if hasattr(field, "native_field") and hasattr(
|
|
724
|
+
field.native_field, "json_schema_extra"
|
|
725
|
+
):
|
|
726
|
+
nested_field_info.update(field.native_field.json_schema_extra or {}) # type: ignore
|
|
727
|
+
|
|
728
|
+
# Render the field
|
|
729
|
+
renderer = get_field_renderer(nested_field_info)
|
|
730
|
+
updated_value[field_name] = renderer(
|
|
731
|
+
key=f"{key}_{field_name}",
|
|
732
|
+
value=field_value,
|
|
733
|
+
label=field_name.replace("_", " ").title(),
|
|
734
|
+
disabled=disabled,
|
|
735
|
+
**nested_field_info,
|
|
736
|
+
)
|
|
737
|
+
|
|
738
|
+
# Add a divider if we're in a container
|
|
739
|
+
if not inside_expander:
|
|
740
|
+
container.divider()
|
|
741
|
+
|
|
742
|
+
# Create a new instance with the updated values
|
|
743
|
+
return fieldz.replace(value, **updated_value)
|
|
744
|
+
except Exception as e: # noqa: BLE001
|
|
745
|
+
st.error(f"Error rendering nested model fields: {e!s}")
|
|
746
|
+
return value
|
|
747
|
+
|
|
748
|
+
|
|
749
|
+
def is_dataclass_like(annotation: Any) -> bool:
|
|
750
|
+
"""Check if a type is a dataclass-like object (Pydantic model, attrs, etc.)."""
|
|
751
|
+
# Check if it's a class
|
|
752
|
+
if not isinstance(annotation, type):
|
|
753
|
+
return False
|
|
754
|
+
|
|
755
|
+
# Check if it's a Pydantic model (v2)
|
|
756
|
+
if hasattr(annotation, "model_fields"):
|
|
757
|
+
return True
|
|
758
|
+
|
|
759
|
+
try:
|
|
760
|
+
# Check if fieldz can extract fields from it
|
|
761
|
+
fields = fieldz.fields(annotation)
|
|
762
|
+
# If we get fields, it's a dataclass-like object
|
|
763
|
+
return len(fields) > 0
|
|
764
|
+
except Exception: # noqa: BLE001
|
|
765
|
+
# If fieldz can't handle it, it's not a dataclass-like object
|
|
766
|
+
return False
|
|
767
|
+
|
|
768
|
+
|
|
769
|
+
# Mapping of Python types to render functions
|
|
770
|
+
PRIMITIVE_RENDERERS = {
|
|
771
|
+
str: render_str_field,
|
|
772
|
+
int: render_int_field,
|
|
773
|
+
float: render_float_field,
|
|
774
|
+
Decimal: render_float_field,
|
|
775
|
+
bool: render_bool_field,
|
|
776
|
+
date: render_date_field,
|
|
777
|
+
time: render_time_field,
|
|
778
|
+
Enum: render_enum_field,
|
|
779
|
+
Literal: render_literal_field,
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
def get_field_renderer(field_info: dict[str, Any]) -> WidgetFunc[Any]: # noqa: PLR0911
|
|
784
|
+
"""Get the appropriate renderer for a field based on its type and constraints."""
|
|
785
|
+
annotation = field_info.get("type") or field_info.get("annotation")
|
|
786
|
+
|
|
787
|
+
# Check for Literal first (using our helper function)
|
|
788
|
+
if is_literal_type(annotation):
|
|
789
|
+
return render_literal_field
|
|
790
|
+
|
|
791
|
+
# Check for Union types
|
|
792
|
+
if is_union_type(annotation):
|
|
793
|
+
return render_union_field
|
|
794
|
+
|
|
795
|
+
# Check for sequence types
|
|
796
|
+
if is_sequence_type(annotation):
|
|
797
|
+
return render_sequence_field
|
|
798
|
+
|
|
799
|
+
# Get basic type (handling Optional/Union)
|
|
800
|
+
origin = get_origin(annotation)
|
|
801
|
+
if origin is not None:
|
|
802
|
+
args = get_args(annotation)
|
|
803
|
+
if len(args) > 0:
|
|
804
|
+
annotation = args[0]
|
|
805
|
+
|
|
806
|
+
# Check if it's a dataclass-like object (including Pydantic models)
|
|
807
|
+
if is_dataclass_like(annotation):
|
|
808
|
+
return render_model_instance_field
|
|
809
|
+
|
|
810
|
+
# Handle Enum types - check explicitly before using issubclass
|
|
811
|
+
if isinstance(annotation, type):
|
|
812
|
+
try:
|
|
813
|
+
if issubclass(annotation, Enum):
|
|
814
|
+
field_info["enum_class"] = annotation
|
|
815
|
+
return render_enum_field
|
|
816
|
+
except TypeError:
|
|
817
|
+
# Skip if we get a TypeError (for special typing constructs)
|
|
818
|
+
pass
|
|
819
|
+
|
|
820
|
+
# Get renderer for basic types - safely check with try/except
|
|
821
|
+
for base_type, renderer in PRIMITIVE_RENDERERS.items():
|
|
822
|
+
if isinstance(annotation, type):
|
|
823
|
+
try:
|
|
824
|
+
if issubclass(annotation, base_type): # type: ignore
|
|
825
|
+
return renderer # type: ignore
|
|
826
|
+
except TypeError:
|
|
827
|
+
# Skip if we get a TypeError (for special typing constructs)
|
|
828
|
+
continue
|
|
829
|
+
|
|
830
|
+
# Special case for Literal (fallback)
|
|
831
|
+
if getattr(annotation, "__origin__", None) is Literal:
|
|
832
|
+
return render_literal_field
|
|
833
|
+
|
|
834
|
+
error_msg = f"No renderer found for type: {annotation}"
|
|
835
|
+
raise ValueError(error_msg)
|
|
836
|
+
|
|
837
|
+
|
|
838
|
+
def render_model_readonly(model_class, instance):
|
|
839
|
+
"""Render a model in read-only mode using a clean label-based layout."""
|
|
840
|
+
if instance is None:
|
|
841
|
+
st.info("No data available")
|
|
842
|
+
return
|
|
843
|
+
|
|
844
|
+
# Create a container for the model display
|
|
845
|
+
with st.container():
|
|
846
|
+
# Get all fields from the model
|
|
847
|
+
for field in fieldz.fields(model_class):
|
|
848
|
+
field_name = field.name
|
|
849
|
+
field_value = getattr(instance, field_name, None)
|
|
850
|
+
|
|
851
|
+
# Get field metadata
|
|
852
|
+
field_type = field.type
|
|
853
|
+
label = field_name.replace("_", " ").title()
|
|
854
|
+
|
|
855
|
+
# Get description if available
|
|
856
|
+
description = None
|
|
857
|
+
if hasattr(field, "metadata") and "description" in field.metadata:
|
|
858
|
+
description = field.metadata["description"]
|
|
859
|
+
elif hasattr(field, "native_field") and hasattr(
|
|
860
|
+
field.native_field, "description"
|
|
861
|
+
):
|
|
862
|
+
description = field.native_field.description # type: ignore
|
|
863
|
+
|
|
864
|
+
# Display field
|
|
865
|
+
render_field_readonly(
|
|
866
|
+
label=label,
|
|
867
|
+
value=field_value,
|
|
868
|
+
field_type=field_type,
|
|
869
|
+
description=description,
|
|
870
|
+
key=f"ro_{field_name}",
|
|
871
|
+
)
|
|
872
|
+
|
|
873
|
+
|
|
874
|
+
def render_field_readonly(label, value, field_type, description=None, key=None):
|
|
875
|
+
"""Render a single field in read-only mode."""
|
|
876
|
+
# Create a container with two columns: label and value
|
|
877
|
+
cols = st.columns([0.3, 0.7])
|
|
878
|
+
|
|
879
|
+
with cols[0]:
|
|
880
|
+
st.markdown(f"**{label}:**")
|
|
881
|
+
if description:
|
|
882
|
+
st.caption(description)
|
|
883
|
+
|
|
884
|
+
with cols[1]:
|
|
885
|
+
display_value_readonly(value, field_type, key)
|
|
886
|
+
|
|
887
|
+
|
|
888
|
+
def display_value_readonly(value, field_type, key=None):
|
|
889
|
+
"""Display a value in read-only mode based on its type."""
|
|
890
|
+
# Handle None values
|
|
891
|
+
if value is None:
|
|
892
|
+
st.text("—") # Em dash to indicate empty value
|
|
893
|
+
return
|
|
894
|
+
|
|
895
|
+
# Handle collections (lists, sets, etc.)
|
|
896
|
+
if is_sequence_type(field_type):
|
|
897
|
+
display_sequence_readonly(value, field_type, key)
|
|
898
|
+
return
|
|
899
|
+
|
|
900
|
+
# Handle nested models
|
|
901
|
+
if is_dataclass_like(field_type):
|
|
902
|
+
display_model_readonly(value, key)
|
|
903
|
+
return
|
|
904
|
+
|
|
905
|
+
# Handle Enum values
|
|
906
|
+
if isinstance(value, Enum):
|
|
907
|
+
st.text(str(value.name))
|
|
908
|
+
return
|
|
909
|
+
|
|
910
|
+
# Handle basic types
|
|
911
|
+
if isinstance(value, bool):
|
|
912
|
+
st.checkbox("", value=value, disabled=True, key=key)
|
|
913
|
+
elif isinstance(value, int | float | Decimal | date | time | datetime):
|
|
914
|
+
st.text(str(value))
|
|
915
|
+
elif isinstance(value, str):
|
|
916
|
+
if len(value) > 100: # Long text # noqa: PLR2004
|
|
917
|
+
st.text_area("", value=value, disabled=True, height=100, key=key)
|
|
918
|
+
else:
|
|
919
|
+
st.text(value)
|
|
920
|
+
else:
|
|
921
|
+
# Default fallback for other types
|
|
922
|
+
st.text(str(value))
|
|
923
|
+
|
|
924
|
+
|
|
925
|
+
def display_sequence_readonly(value, field_type, key=None):
|
|
926
|
+
"""Display a sequence (list, set, tuple) in read-only mode."""
|
|
927
|
+
if not value: # Empty sequence
|
|
928
|
+
st.text("No items")
|
|
929
|
+
return
|
|
930
|
+
|
|
931
|
+
# Get item type
|
|
932
|
+
item_type = Any
|
|
933
|
+
with contextlib.suppress(IndexError, TypeError):
|
|
934
|
+
item_type = get_args(field_type)[0]
|
|
935
|
+
|
|
936
|
+
# Display each item
|
|
937
|
+
for i, item in enumerate(value):
|
|
938
|
+
with st.expander(f"Item {i + 1}", expanded=False):
|
|
939
|
+
display_value_readonly(item, item_type, key=f"{key}_{i}" if key else None)
|
|
940
|
+
|
|
941
|
+
|
|
942
|
+
def display_model_readonly(value, key=None):
|
|
943
|
+
"""Display a nested model in read-only mode."""
|
|
944
|
+
# Get model class
|
|
945
|
+
model_class = value.__class__
|
|
946
|
+
|
|
947
|
+
# Get all fields
|
|
948
|
+
for field in fieldz.fields(model_class):
|
|
949
|
+
field_name = field.name
|
|
950
|
+
field_value = getattr(value, field_name, None)
|
|
951
|
+
|
|
952
|
+
# Handle 'MISSING' values
|
|
953
|
+
if field_value == "MISSING":
|
|
954
|
+
field_value = _get_with_default(value, field_name, field)
|
|
955
|
+
|
|
956
|
+
# Create a sub-container for this field
|
|
957
|
+
sub_key = f"{key}_{field_name}" if key else field_name
|
|
958
|
+
|
|
959
|
+
cols = st.columns([0.3, 0.7])
|
|
960
|
+
with cols[0]:
|
|
961
|
+
st.markdown(f"**{field_name.replace('_', ' ').title()}:**")
|
|
962
|
+
with cols[1]:
|
|
963
|
+
display_value_readonly(field_value, field.type, key=sub_key)
|
|
964
|
+
|
|
965
|
+
|
|
966
|
+
def render_model_field(model_class, field_name, value=None):
|
|
967
|
+
"""Render a field from a model using fieldz to extract field information."""
|
|
968
|
+
field = next((f for f in fieldz.fields(model_class) if f.name == field_name), None)
|
|
969
|
+
|
|
970
|
+
if field is None:
|
|
971
|
+
error_msg = f"Field {field_name} not found in {model_class.__name__}"
|
|
972
|
+
raise ValueError(error_msg)
|
|
973
|
+
|
|
974
|
+
# Extract field information using fieldz
|
|
975
|
+
field_info = {
|
|
976
|
+
"name": field.name,
|
|
977
|
+
"type": field.type,
|
|
978
|
+
"default": field.default,
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
# Extract additional properties from field metadata
|
|
982
|
+
if hasattr(field, "native_field") and hasattr(
|
|
983
|
+
field.native_field, "json_schema_extra"
|
|
984
|
+
):
|
|
985
|
+
field_info.update(field.native_field.json_schema_extra or {}) # pyright: ignore
|
|
986
|
+
|
|
987
|
+
# Get description for the label
|
|
988
|
+
label = field_name.replace("_", " ").title()
|
|
989
|
+
if hasattr(field, "metadata") and "description" in field.metadata:
|
|
990
|
+
description = field.metadata["description"]
|
|
991
|
+
field_info["description"] = description
|
|
992
|
+
elif hasattr(field, "native_field") and hasattr(field.native_field, "description"):
|
|
993
|
+
description = field.native_field.description # pyright: ignore
|
|
994
|
+
field_info["description"] = description
|
|
995
|
+
|
|
996
|
+
# Get renderer and render the field
|
|
997
|
+
renderer = get_field_renderer(field_info)
|
|
998
|
+
return renderer(
|
|
999
|
+
key=field_name,
|
|
1000
|
+
value=value,
|
|
1001
|
+
label=label,
|
|
1002
|
+
**field_info,
|
|
1003
|
+
)
|
|
1004
|
+
|
|
1005
|
+
|
|
1006
|
+
TForm = TypeVar("TForm", bound="BaseModel")
|
|
1007
|
+
|
|
1008
|
+
|
|
1009
|
+
@overload
|
|
1010
|
+
def render_model_form(
|
|
1011
|
+
model_or_instance: type[TForm], *, readonly: bool = False
|
|
1012
|
+
) -> TForm: ...
|
|
1013
|
+
|
|
1014
|
+
|
|
1015
|
+
@overload
|
|
1016
|
+
def render_model_form(model_or_instance: TForm, *, readonly: bool = False) -> TForm: ...
|
|
1017
|
+
|
|
1018
|
+
|
|
1019
|
+
def render_model_form(model_or_instance, *, readonly: bool = False) -> Any:
|
|
1020
|
+
"""Render a complete form for a model class or instance.
|
|
1021
|
+
|
|
1022
|
+
Args:
|
|
1023
|
+
model_or_instance: Either a model class or an instance of it
|
|
1024
|
+
readonly: Whether to render in read-only mode
|
|
1025
|
+
|
|
1026
|
+
Returns:
|
|
1027
|
+
An instance of the model with updated values
|
|
1028
|
+
"""
|
|
1029
|
+
# Determine if we have a class or an instance
|
|
1030
|
+
if isinstance(model_or_instance, type):
|
|
1031
|
+
# We received a class
|
|
1032
|
+
model_class = model_or_instance
|
|
1033
|
+
instance = model_class() # Create a default instance
|
|
1034
|
+
else:
|
|
1035
|
+
# We received an instance
|
|
1036
|
+
instance = model_or_instance
|
|
1037
|
+
model_class = instance.__class__
|
|
1038
|
+
if readonly:
|
|
1039
|
+
render_model_readonly(model_class, instance)
|
|
1040
|
+
return instance # No changes in read-only mode
|
|
1041
|
+
|
|
1042
|
+
# Interactive form rendering
|
|
1043
|
+
result = {}
|
|
1044
|
+
|
|
1045
|
+
for field in fieldz.fields(model_class):
|
|
1046
|
+
field_name = field.name
|
|
1047
|
+
# Use _get_with_default to handle 'MISSING' values
|
|
1048
|
+
current_value = _get_with_default(instance, field_name, field)
|
|
1049
|
+
|
|
1050
|
+
st.subheader(field_name.replace("_", " ").title())
|
|
1051
|
+
|
|
1052
|
+
# Display field description if available
|
|
1053
|
+
description = None
|
|
1054
|
+
if hasattr(field, "metadata") and "description" in field.metadata:
|
|
1055
|
+
description = field.metadata["description"]
|
|
1056
|
+
elif hasattr(field, "native_field") and hasattr(
|
|
1057
|
+
field.native_field, "description"
|
|
1058
|
+
):
|
|
1059
|
+
description = field.native_field.description # type: ignore
|
|
1060
|
+
|
|
1061
|
+
if description:
|
|
1062
|
+
st.caption(description)
|
|
1063
|
+
|
|
1064
|
+
# Render the field and store the result
|
|
1065
|
+
result[field_name] = render_model_field(model_class, field_name, current_value)
|
|
1066
|
+
|
|
1067
|
+
# Create a new instance with updated values
|
|
1068
|
+
return fieldz.replace(instance, **result)
|
|
1069
|
+
|
|
1070
|
+
|
|
1071
|
+
if __name__ == "__main__":
|
|
1072
|
+
from typing import Literal
|
|
1073
|
+
|
|
1074
|
+
from pydantic import BaseModel, Field
|
|
1075
|
+
|
|
1076
|
+
from streambricks.helpers import run
|
|
1077
|
+
|
|
1078
|
+
class SubModel(BaseModel):
|
|
1079
|
+
"""Test submodel."""
|
|
1080
|
+
|
|
1081
|
+
name: str
|
|
1082
|
+
value: int | float
|
|
1083
|
+
active: bool = True
|
|
1084
|
+
|
|
1085
|
+
class TestModel(BaseModel):
|
|
1086
|
+
"""Test model."""
|
|
1087
|
+
|
|
1088
|
+
status: int | str | bool = Field(
|
|
1089
|
+
2, description="A field that can be either int, str, or bool"
|
|
1090
|
+
)
|
|
1091
|
+
optional_text: str | None = Field(None, description="Optional text field")
|
|
1092
|
+
|
|
1093
|
+
# Lists with various types
|
|
1094
|
+
tags: list[str] = Field(default_factory=list, description="A list of string tags")
|
|
1095
|
+
numbers: list[int | float] = Field(
|
|
1096
|
+
default_factory=list, description="A list of numbers (int or float)"
|
|
1097
|
+
)
|
|
1098
|
+
|
|
1099
|
+
# Nested structures
|
|
1100
|
+
settings: list[SubModel] = Field(
|
|
1101
|
+
default_factory=list, description="A list of nested models"
|
|
1102
|
+
)
|
|
1103
|
+
|
|
1104
|
+
# Combined with literals
|
|
1105
|
+
priorities: list[Literal["Low", "Medium", "High"]] = Field(
|
|
1106
|
+
default_factory=list, description="A list of priority levels"
|
|
1107
|
+
)
|
|
1108
|
+
|
|
1109
|
+
def demo():
|
|
1110
|
+
st.title("Pydantic Form Demo")
|
|
1111
|
+
|
|
1112
|
+
# Initialize or get model from session state
|
|
1113
|
+
if "model" not in st.session_state:
|
|
1114
|
+
st.session_state.model = TestModel(status=2, optional_text=None)
|
|
1115
|
+
|
|
1116
|
+
# Render the complete form and update the model
|
|
1117
|
+
st.session_state.model = render_model_form(TestModel)
|
|
1118
|
+
|
|
1119
|
+
# Display current model state
|
|
1120
|
+
with st.expander("Current Model State", expanded=True):
|
|
1121
|
+
st.json(st.session_state.model.model_dump_json(indent=2))
|
|
1122
|
+
|
|
1123
|
+
run(demo)
|