datamuo 1.1.24__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.
- datamuo/__init__.py +17 -0
- datamuo/_reports.py +407 -0
- datamuo/_runtime.py +65 -0
- datamuo/actions.js +64 -0
- datamuo/bin/Enterprise.DataTensor.dll +0 -0
- datamuo/bin/Enterprise.Fragments.dll +0 -0
- datamuo/bin/Enterprise.Reporting.dll +0 -0
- datamuo/bin/Enterprise.Utils.dll +0 -0
- datamuo/py.typed +0 -0
- datamuo/runtimeconfig.json +10 -0
- datamuo-1.1.24.dist-info/METADATA +134 -0
- datamuo-1.1.24.dist-info/RECORD +14 -0
- datamuo-1.1.24.dist-info/WHEEL +4 -0
- datamuo-1.1.24.dist-info/licenses/LICENSE.txt +22 -0
datamuo/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Muoland.Reporting from Python: tensors of records, interactive (pivot) tables rendered as HTML, comments.
|
|
2
|
+
|
|
3
|
+
tensor = Tensor("System", records) # shared by all users
|
|
4
|
+
report = tensor.table(order=["name"], page_size=50) # one per user session
|
|
5
|
+
fragments = report.render() # then report.render(action) on each user interaction
|
|
6
|
+
assets() # CSS and JavaScript the page loads once
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from ._reports import (
|
|
10
|
+
Assets, Comment, DimensionMember, Fragments, Record, Report, ReportOptions, Tensor, UiTreeBuilder, View, assets, deserialize,
|
|
11
|
+
)
|
|
12
|
+
from ._runtime import ReportingError
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"Assets", "Comment", "DimensionMember", "Fragments", "Record", "Report", "ReportOptions", "ReportingError", "Tensor",
|
|
16
|
+
"UiTreeBuilder", "View", "assets", "deserialize",
|
|
17
|
+
]
|
datamuo/_reports.py
ADDED
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
"""Tensors (shared records and comments) and the interactive reports rendering them as HTML fragments."""
|
|
2
|
+
|
|
3
|
+
import functools
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
import threading
|
|
8
|
+
from collections.abc import Callable, Iterable, Mapping, Sequence
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from datetime import UTC, datetime
|
|
11
|
+
from operator import attrgetter
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any, Final, Literal, TypedDict, Unpack
|
|
14
|
+
|
|
15
|
+
from ._runtime import ReportingError, dotnet, strings, translate_errors
|
|
16
|
+
|
|
17
|
+
type Record = dict[str, Any]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True, slots=True)
|
|
21
|
+
class View:
|
|
22
|
+
"""A saved state of a report: slices, expanded rows and columns, and filters."""
|
|
23
|
+
|
|
24
|
+
name: str
|
|
25
|
+
row_slices: tuple[str, ...] = ()
|
|
26
|
+
column_slices: tuple[str, ...] = ()
|
|
27
|
+
open_rows: tuple[tuple[str, ...], ...] = () # data point tags of the expanded rows
|
|
28
|
+
open_columns: tuple[tuple[str, ...], ...] = ()
|
|
29
|
+
filters: Mapping[str, tuple[str, ...]] = field(default_factory=dict[str, tuple[str, ...]]) # values kept by dimension
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True, slots=True)
|
|
33
|
+
class Comment:
|
|
34
|
+
"""A comment on a data point of a tensor."""
|
|
35
|
+
|
|
36
|
+
tag: tuple[str, ...] # the data point's dimension values, in dimension order
|
|
37
|
+
author: str
|
|
38
|
+
text: str
|
|
39
|
+
priority: int = 1 # lower is more critical
|
|
40
|
+
created: datetime = field(default_factory=lambda: datetime.now(UTC))
|
|
41
|
+
view: View | None = None # the report view it refers to
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def key(self) -> str:
|
|
45
|
+
"""The tag as the engine keys data points."""
|
|
46
|
+
return ",".join(self.tag)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True, slots=True)
|
|
50
|
+
class DimensionMember:
|
|
51
|
+
"""A value of a dimension, as in the records, with how to display it and its place among the others."""
|
|
52
|
+
|
|
53
|
+
name: str
|
|
54
|
+
display_name: str | None = None # defaults to the name
|
|
55
|
+
parent: str | None = None
|
|
56
|
+
order: int = 0
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(frozen=True, slots=True)
|
|
60
|
+
class Fragments:
|
|
61
|
+
"""HTML of each report area; the `assets()` script turns interactions with it into `mlu-action` events."""
|
|
62
|
+
|
|
63
|
+
main: str
|
|
64
|
+
filter: str
|
|
65
|
+
comments: str
|
|
66
|
+
dialogs: str
|
|
67
|
+
view: str
|
|
68
|
+
slice: str
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass(frozen=True, slots=True)
|
|
72
|
+
class Assets:
|
|
73
|
+
"""CSS (icons included) and JavaScript (interactions included) a page loads once to display any report."""
|
|
74
|
+
|
|
75
|
+
css: str
|
|
76
|
+
js: str
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class UiTreeBuilder:
|
|
80
|
+
"""Draws the HTML of a cell for `ReportOptions.custom_views`; markup content is inserted as is."""
|
|
81
|
+
|
|
82
|
+
__slots__ = ("_builder",)
|
|
83
|
+
|
|
84
|
+
def __init__(self, builder: Any) -> None:
|
|
85
|
+
self._builder = builder
|
|
86
|
+
|
|
87
|
+
def open_element(self, name: str) -> None:
|
|
88
|
+
self._builder.OpenElement(name)
|
|
89
|
+
|
|
90
|
+
def add_attribute(self, name: str, value: str | int | float | bool) -> None:
|
|
91
|
+
self._builder.AddAttribute(name, value)
|
|
92
|
+
|
|
93
|
+
def add_markup_content(self, markup: str) -> None:
|
|
94
|
+
self._builder.AddMarkupContent(markup)
|
|
95
|
+
|
|
96
|
+
def close_element(self) -> None:
|
|
97
|
+
self._builder.CloseElement()
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class ReportOptions(TypedDict, total=False):
|
|
101
|
+
"""Options of a table or pivot table; callbacks get the report and records as plain Python values."""
|
|
102
|
+
|
|
103
|
+
order: Sequence[str] # properties shown first, in this order
|
|
104
|
+
hidden: Sequence[str]
|
|
105
|
+
page_size: int
|
|
106
|
+
height: str # CSS length, e.g. "65vh"
|
|
107
|
+
width: str
|
|
108
|
+
cell_width: int # pixels, of pivot table cells
|
|
109
|
+
table_style: str # inline CSS of the table
|
|
110
|
+
theme: Literal["minimalist", "simplified"]
|
|
111
|
+
centered: bool
|
|
112
|
+
editable: Sequence[str] # properties users can edit, all by default
|
|
113
|
+
validate: Callable[["Report", Record], Sequence[str]] # errors rejecting an edited record
|
|
114
|
+
on_submit: Callable[["Report", Record], None] # each valid edited record
|
|
115
|
+
on_row_click: Callable[["Report", Record], None] # instead of opening the record dialog
|
|
116
|
+
custom_views: Mapping[str, Callable[[UiTreeBuilder, Any], None]] # draws the cells of a property from their value
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _action(callback: Callable[["Report", Record], None], report: Callable[[], "Report"]) -> Any:
|
|
120
|
+
net = dotnet()
|
|
121
|
+
|
|
122
|
+
def action(_: Any, record: Any) -> None:
|
|
123
|
+
callback(report(), _py(record))
|
|
124
|
+
|
|
125
|
+
return net.Action[net.Object, net.Object](action)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _validation(validate: Callable[["Report", Record], Sequence[str]], report: Callable[[], "Report"]) -> Any:
|
|
129
|
+
net = dotnet()
|
|
130
|
+
|
|
131
|
+
def rules(_: Any, record: Any) -> Any:
|
|
132
|
+
return net.List[net.String](strings(validate(report(), _py(record))))
|
|
133
|
+
|
|
134
|
+
return net.Func[net.Object, net.Object, net.List[net.String]](rules)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _custom_views(options: Any, views: Mapping[str, Callable[[UiTreeBuilder, Any], None]]) -> Any:
|
|
138
|
+
net = dotnet()
|
|
139
|
+
for prop, draw in views.items():
|
|
140
|
+
|
|
141
|
+
def view(builder: Any, value: Any, draw: Callable[[UiTreeBuilder, Any], None] = draw) -> None:
|
|
142
|
+
draw(UiTreeBuilder(builder), _py(value))
|
|
143
|
+
|
|
144
|
+
options = options.WithCustomView(prop, net.Func[net.Object, net.Object, net.String](view))
|
|
145
|
+
return options
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
# option -> (engine options, value, the report once created) -> engine options
|
|
149
|
+
_OPTIONS: dict[str, Callable[[Any, Any, Callable[[], "Report"]], Any]] = {
|
|
150
|
+
"order": lambda options, value, _: options.WithOrderedProperties(strings(value)),
|
|
151
|
+
"hidden": lambda options, value, _: options.WithHiddenProperties(strings(value)),
|
|
152
|
+
"page_size": lambda options, value, _: options.WithItemsPerPage(value),
|
|
153
|
+
"height": lambda options, value, _: options.WithTableHeight(value),
|
|
154
|
+
"width": lambda options, value, _: options.WithTableWidth(value),
|
|
155
|
+
"cell_width": lambda options, value, _: options.WithCellWidth(value),
|
|
156
|
+
"table_style": lambda options, value, _: options.WithTableStyle(value),
|
|
157
|
+
"theme": lambda options, value, _: options.MinimalistStyle() if value == "minimalist" else options.SimplifiedStyle(),
|
|
158
|
+
"centered": lambda options, value, _: options.Center() if value else options,
|
|
159
|
+
"editable": lambda options, value, _: options.WithEditableProperties(strings(value)),
|
|
160
|
+
"validate": lambda options, value, report: options.WithValidationRules(_validation(value, report)),
|
|
161
|
+
"on_submit": lambda options, value, report: options.WithSubmissionAction(_action(value, report)),
|
|
162
|
+
"on_row_click": lambda options, value, report: options.WithOnClickRow(_action(value, report)),
|
|
163
|
+
"custom_views": lambda options, value, _: _custom_views(options, value),
|
|
164
|
+
}
|
|
165
|
+
# Fragments field -> engine name of its area
|
|
166
|
+
_AREAS = {"main": "Main", "filter": "FilterWidget", "comments": "CommentWidget", "dialogs": "Dialogs", "view": "ViewWidget", "slice": "SliceWidget"}
|
|
167
|
+
_BLANK = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
@functools.cache
|
|
171
|
+
def _icons() -> dict[str, str]:
|
|
172
|
+
"""Base64 PNG of each icon by the file name the HTML references, e.g. "add.png"."""
|
|
173
|
+
return {str(icon.Key): str(icon.Value) for icon in dotnet().Report.IconsByName}
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@functools.cache
|
|
177
|
+
def _icon_src() -> re.Pattern[str]:
|
|
178
|
+
return re.compile('src="({})"'.format("|".join(map(re.escape, _icons()))))
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
@functools.cache
|
|
182
|
+
def assets() -> Assets:
|
|
183
|
+
"""The CSS and JavaScript every page displaying reports must load once."""
|
|
184
|
+
net = dotnet()
|
|
185
|
+
with translate_errors():
|
|
186
|
+
css = str(net.CssStyle.Get().ToHtml()).strip().removeprefix("<style>").removesuffix("</style>")
|
|
187
|
+
icons = "".join(
|
|
188
|
+
f'img[data-mlu-icon="{name}"]{{background:url(data:image/png;base64,{data}) center/contain no-repeat}}'
|
|
189
|
+
for name, data in _icons().items()
|
|
190
|
+
)
|
|
191
|
+
# icons first: the engine CSS leaves a block unclosed, which would nest anything appended after it
|
|
192
|
+
actions = Path(__file__).with_name("actions.js").read_text(encoding="utf-8")
|
|
193
|
+
return Assets(css=icons + css, js=f"{net.Report.JSScripts}\n{actions}")
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _value(value: Any) -> Any:
|
|
197
|
+
# the engine can neither aggregate nulls nor parse NaN or infinity
|
|
198
|
+
return "" if value is None or isinstance(value, float) and not math.isfinite(value) else value
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _json(record: Mapping[str, Any]) -> str:
|
|
202
|
+
# tensor data and comment lookups must serialize records alike
|
|
203
|
+
return json.dumps({key: _value(value) for key, value in record.items()}, default=str)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _py(value: Any) -> Any:
|
|
207
|
+
"""An engine value as plain Python, e.g. a record as a dict."""
|
|
208
|
+
net = dotnet()
|
|
209
|
+
if isinstance(value, net.IDictionary):
|
|
210
|
+
return {str(key): _py(value[key]) for key in value.Keys}
|
|
211
|
+
if isinstance(value, net.IList):
|
|
212
|
+
return [_py(item) for item in value]
|
|
213
|
+
return value
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _strs(items: Any) -> tuple[str, ...]:
|
|
217
|
+
return tuple(map(str, items or ()))
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _view(view: Any) -> View:
|
|
221
|
+
filters = view.FiltersByDimension
|
|
222
|
+
return View(
|
|
223
|
+
name=str(view.Name),
|
|
224
|
+
row_slices=_strs(view.RowSlices),
|
|
225
|
+
column_slices=_strs(view.ColumnSlices),
|
|
226
|
+
open_rows=tuple(map(_strs, view.RowsOpenStringTags or ())),
|
|
227
|
+
open_columns=tuple(map(_strs, view.ColumnsOpenStringTags or ())),
|
|
228
|
+
filters={str(dimension): _strs(filters[dimension]) for dimension in filters.Keys} if filters else {},
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _net_tags(tags: Iterable[Iterable[str]]) -> Any:
|
|
233
|
+
net = dotnet()
|
|
234
|
+
return net.Array[net.StringValues]([net.StringValues(strings(tag)) for tag in tags])
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _net_view(view: View) -> Any:
|
|
238
|
+
net = dotnet()
|
|
239
|
+
filters = net.Dictionary[net.String, net.Array[net.String]]()
|
|
240
|
+
for dimension, kept in view.filters.items():
|
|
241
|
+
filters[dimension] = strings(kept)
|
|
242
|
+
return net.DataView(
|
|
243
|
+
view.name, strings(view.row_slices), strings(view.column_slices), _net_tags(view.open_rows), _net_tags(view.open_columns), filters
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _comment(comment: Any) -> Comment:
|
|
248
|
+
return Comment(
|
|
249
|
+
tag=_strs(comment.StringTag),
|
|
250
|
+
author=str(comment.Author),
|
|
251
|
+
text=str(comment.Text),
|
|
252
|
+
priority=int(comment.Priority),
|
|
253
|
+
created=datetime.fromisoformat(str(comment.DateTime.ToString("o"))),
|
|
254
|
+
view=None if comment.View is None else _view(comment.View),
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _net_comment(comment: Comment) -> Any:
|
|
259
|
+
net = dotnet()
|
|
260
|
+
view = None if comment.view is None else _net_view(comment.view)
|
|
261
|
+
engine_comment = net.DataComment(net.StringValues(strings(comment.tag)), comment.priority, comment.text, comment.author, view)
|
|
262
|
+
engine_comment.DateTime = net.DateTimeOffset.Parse(comment.created.isoformat(), net.CultureInfo.InvariantCulture).UtcDateTime
|
|
263
|
+
return engine_comment
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _member(member: DimensionMember) -> str:
|
|
267
|
+
display_name = member.display_name or member.name
|
|
268
|
+
return json.dumps({"SystemName": member.name, "DisplayName": display_name, "Parent": member.parent, "Order": member.order})
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _commit[T](kind: Any, convert: Callable[[Any], T], callback: Callable[[T], None] | None) -> Any:
|
|
272
|
+
"""An engine callback passing each new comment or view to `callback`."""
|
|
273
|
+
net = dotnet()
|
|
274
|
+
|
|
275
|
+
def commit(item: Any) -> Any:
|
|
276
|
+
if callback:
|
|
277
|
+
callback(convert(item))
|
|
278
|
+
return net.Task.CompletedTask
|
|
279
|
+
|
|
280
|
+
return net.Func[kind, net.Task](commit)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _ensure_healthy(subject: str, healthy: bool, errors: Any) -> None:
|
|
284
|
+
if not healthy or errors:
|
|
285
|
+
raise ReportingError(f"{subject} is unhealthy: {'; '.join(map(str, errors or ())) or 'no details'}")
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
class Report:
|
|
289
|
+
"""A table or pivot table from `Tensor.table`/`Tensor.pivot`, with its own UI state: use one per user session."""
|
|
290
|
+
|
|
291
|
+
def __init__(self, name: str, report: Any, lock: threading.RLock) -> None:
|
|
292
|
+
self._name, self._report, self._lock = name, report, lock
|
|
293
|
+
_ensure_healthy(f"Report {name!r}", report.Status, report.Errors)
|
|
294
|
+
|
|
295
|
+
def render(self, action: str = "") -> Fragments:
|
|
296
|
+
"""Apply a user action, i.e. the `detail.action` of an `mlu-action` event, and return the new HTML."""
|
|
297
|
+
with self._lock, translate_errors():
|
|
298
|
+
if action:
|
|
299
|
+
self._report.HandleUserAction(action)
|
|
300
|
+
for area in _AREAS.values():
|
|
301
|
+
getattr(self._report, f"Eval{area}Fragment")()
|
|
302
|
+
_ensure_healthy(f"Report {self._name!r}", self._report.Status, self._report.Errors)
|
|
303
|
+
# icons reference files no host serves: swap in a placeholder showing the icon from the `assets()` CSS
|
|
304
|
+
icon_src, placeholder = _icon_src(), rf'src="{_BLANK}" data-mlu-icon="\1"'
|
|
305
|
+
return Fragments(**{
|
|
306
|
+
field: icon_src.sub(placeholder, str(getattr(self._report, f"{area}UiTree").ToHtml()))
|
|
307
|
+
for field, area in _AREAS.items()
|
|
308
|
+
})
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
class Tensor:
|
|
312
|
+
"""Records organised by dimensions, plus their comments; thread-safe and shared by all reports built on it."""
|
|
313
|
+
|
|
314
|
+
def __init__(
|
|
315
|
+
self,
|
|
316
|
+
name: str,
|
|
317
|
+
records: Iterable[Mapping[str, Any]],
|
|
318
|
+
*,
|
|
319
|
+
dimensions: Sequence[str] = ("id",),
|
|
320
|
+
values: Sequence[str] | None = None,
|
|
321
|
+
aggregations: Mapping[str, Callable[[Any, Any], Any]] | None = None,
|
|
322
|
+
dimension_data: Mapping[str, Iterable[DimensionMember]] | None = None,
|
|
323
|
+
comments: Iterable[Comment] = (),
|
|
324
|
+
on_comment: Callable[[Comment], None] | None = None,
|
|
325
|
+
views: Iterable[View] = (),
|
|
326
|
+
on_view: Callable[[View], None] | None = None,
|
|
327
|
+
) -> None:
|
|
328
|
+
"""`values` default to all other record properties; `None`, NaN and infinite values become empty strings.
|
|
329
|
+
|
|
330
|
+
An aggregation folds two values of a property into one, e.g. `max`. `dimension_data` describes the values of
|
|
331
|
+
dimensions. `comments` and `views` restore those saved by `on_comment` and `on_view`, which may run on another
|
|
332
|
+
thread.
|
|
333
|
+
"""
|
|
334
|
+
net = dotnet()
|
|
335
|
+
rows = list(records)
|
|
336
|
+
if values is None:
|
|
337
|
+
values = [key for key in dict.fromkeys(key for row in rows for key in row) if key not in dimensions]
|
|
338
|
+
self.name: Final = name
|
|
339
|
+
self._lock = threading.RLock()
|
|
340
|
+
with translate_errors():
|
|
341
|
+
builder = (
|
|
342
|
+
net.DataTensorBuilder.WithData(strings(map(_json, rows)))
|
|
343
|
+
.WithComments(net.Array[net.DataComment](list(map(_net_comment, comments))), _commit(net.DataComment, _comment, on_comment))
|
|
344
|
+
.WithViews(net.Array[net.DataView](list(map(_net_view, views))), _commit(net.DataView, _view, on_view))
|
|
345
|
+
.WithDimensionProperties(strings(dimensions))
|
|
346
|
+
.WithValueProperties(strings(values))
|
|
347
|
+
)
|
|
348
|
+
for dimension, members in (dimension_data or {}).items():
|
|
349
|
+
builder = builder.WithDimensionData(strings(map(_member, members)), dimension)
|
|
350
|
+
for prop, aggregate in (aggregations or {}).items():
|
|
351
|
+
builder = builder.WithCustomAggregation(prop, net.Func[net.Object, net.Object, net.Object](aggregate))
|
|
352
|
+
self._tensor = builder.Create()
|
|
353
|
+
_ensure_healthy(f"Tensor {name!r}", self._tensor.IsHealthy, self._tensor.Errors)
|
|
354
|
+
|
|
355
|
+
def table(self, **options: Unpack[ReportOptions]) -> Report:
|
|
356
|
+
"""A new paged table of the records."""
|
|
357
|
+
return self._report(options, lambda report: report.ToTable())
|
|
358
|
+
|
|
359
|
+
def pivot(self, rows: Sequence[str] = (), columns: Sequence[str] = (), **options: Unpack[ReportOptions]) -> Report:
|
|
360
|
+
"""A new pivot table aggregating the values over the given row and column dimensions."""
|
|
361
|
+
|
|
362
|
+
def sliced(report: Any) -> Any:
|
|
363
|
+
pivot = report.ToPivotTable()
|
|
364
|
+
if rows:
|
|
365
|
+
pivot.SliceRowsBy(strings(rows))
|
|
366
|
+
if columns:
|
|
367
|
+
pivot.SliceColumnsBy(strings(columns))
|
|
368
|
+
return pivot
|
|
369
|
+
|
|
370
|
+
return self._report(options, sliced)
|
|
371
|
+
|
|
372
|
+
def add_comment(self, record: Mapping[str, Any], text: str, *, author: str, priority: int = 1) -> None:
|
|
373
|
+
"""Comment the record's data point; lower priorities are more critical."""
|
|
374
|
+
with self._lock, translate_errors():
|
|
375
|
+
committing = self._tensor.AddComment(_json(record), priority, author, text, None)
|
|
376
|
+
with translate_errors(): # outside the lock, which `on_comment` may need on the engine's thread
|
|
377
|
+
committing.GetAwaiter().GetResult()
|
|
378
|
+
|
|
379
|
+
def comments(self, record: Mapping[str, Any] | None = None) -> list[Comment]:
|
|
380
|
+
"""Comment history, oldest first, of the record's data point or of all data points."""
|
|
381
|
+
with self._lock, translate_errors():
|
|
382
|
+
if record is None:
|
|
383
|
+
found = [comment for history in self._tensor.GetIndexedComments().Values for comment in history]
|
|
384
|
+
else:
|
|
385
|
+
found = self._tensor.GetComments(_json(record))
|
|
386
|
+
return sorted(map(_comment, found), key=attrgetter("created"))
|
|
387
|
+
|
|
388
|
+
def _report(self, options: ReportOptions, shape: Callable[[Any], Any]) -> Report:
|
|
389
|
+
net = dotnet()
|
|
390
|
+
options_type = net.ReportOptions[net.Dictionary[net.String, net.Object]]
|
|
391
|
+
created: list[Report] = []
|
|
392
|
+
|
|
393
|
+
def configure(engine_options: Any) -> Any:
|
|
394
|
+
for option, value in options.items():
|
|
395
|
+
engine_options = _OPTIONS[option](engine_options, value, lambda: created[0])
|
|
396
|
+
return engine_options
|
|
397
|
+
|
|
398
|
+
with self._lock, translate_errors():
|
|
399
|
+
builder = net.ReportBuilder.FromTensor(self._tensor, self.name).WithOptions(net.Func[options_type, options_type](configure))
|
|
400
|
+
created.append(Report(self.name, shape(builder.Create()), self._lock))
|
|
401
|
+
return created[0]
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def deserialize(records: Iterable[str]) -> list[Record]:
|
|
405
|
+
"""JSON records as the engine reads them: dicts sharing all keys, the missing ones set to `None`."""
|
|
406
|
+
with translate_errors():
|
|
407
|
+
return [_py(record) for record in dotnet().DataTensorBuilder.Deserialize(strings(records))]
|
datamuo/_runtime.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Starts .NET with the Muoland.Reporting assemblies bundled in this package."""
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import functools
|
|
5
|
+
import importlib
|
|
6
|
+
import threading
|
|
7
|
+
from collections.abc import Generator, Iterable
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from types import SimpleNamespace
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
_BIN = Path(__file__).with_name("bin")
|
|
13
|
+
_lock = threading.Lock()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ReportingError(Exception):
|
|
17
|
+
"""The reporting engine could not start or failed to process the data."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@functools.cache
|
|
21
|
+
def _start() -> SimpleNamespace:
|
|
22
|
+
assemblies = sorted(_BIN.glob("*.dll"))
|
|
23
|
+
if not assemblies:
|
|
24
|
+
raise ReportingError(f"No Muoland.Reporting assemblies in {_BIN}, the package was built without them")
|
|
25
|
+
try:
|
|
26
|
+
importlib.import_module("pythonnet").load("coreclr", runtime_config=str(_BIN.with_name("runtimeconfig.json")))
|
|
27
|
+
clr = importlib.import_module("clr")
|
|
28
|
+
for assembly in assemblies:
|
|
29
|
+
clr.AddReference(str(assembly))
|
|
30
|
+
except Exception as error:
|
|
31
|
+
raise ReportingError(f"Cannot start Muoland.Reporting, is the ASP.NET Core 10 runtime installed? {error}") from error
|
|
32
|
+
system, collections, generic, globalization, tasks, primitives, tensor, fragments, reporting = map(importlib.import_module, (
|
|
33
|
+
"System", "System.Collections", "System.Collections.Generic", "System.Globalization", "System.Threading.Tasks",
|
|
34
|
+
"Microsoft.Extensions.Primitives", "Enterprise.DataTensor", "Enterprise.Fragments", "Enterprise.Reporting",
|
|
35
|
+
))
|
|
36
|
+
return SimpleNamespace(
|
|
37
|
+
Action=system.Action, Array=system.Array, DateTimeOffset=system.DateTimeOffset, Exception=system.Exception,
|
|
38
|
+
Func=system.Func, Object=system.Object, String=system.String, IDictionary=collections.IDictionary,
|
|
39
|
+
IList=collections.IList, Dictionary=generic.Dictionary, List=generic.List, CultureInfo=globalization.CultureInfo,
|
|
40
|
+
Task=tasks.Task, StringValues=primitives.StringValues, DataComment=tensor.DataComment,
|
|
41
|
+
DataTensorBuilder=tensor.DataTensorBuilder, DataView=tensor.DataView, CssStyle=fragments.CssStyle,
|
|
42
|
+
Report=reporting.Report, ReportBuilder=reporting.ReportBuilder, ReportOptions=reporting.ReportOptions,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def dotnet() -> SimpleNamespace:
|
|
47
|
+
"""The .NET types the wrapper uses; the first call starts the runtime."""
|
|
48
|
+
with _lock:
|
|
49
|
+
return _start()
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def strings(items: Iterable[str]) -> Any:
|
|
53
|
+
"""A .NET string array, which pythonnet does not create from lists for `IEnumerable<string>` parameters."""
|
|
54
|
+
net = dotnet()
|
|
55
|
+
return net.Array[net.String](list(items))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@contextlib.contextmanager
|
|
59
|
+
def translate_errors() -> Generator[None]:
|
|
60
|
+
"""Re-raise .NET exceptions as `ReportingError`, so callers never deal with pythonnet types."""
|
|
61
|
+
try:
|
|
62
|
+
yield
|
|
63
|
+
except dotnet().Exception as error:
|
|
64
|
+
# the message only: str() of a .NET exception includes its stack trace, kept in __cause__
|
|
65
|
+
raise ReportingError(str(error.Message)) from error
|
datamuo/actions.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// Turns user interactions with report HTML into bubbling "mlu-action" events: the host sends each
|
|
2
|
+
// event.detail.action to Report.render and applies the returned HTML unless event.detail.silent.
|
|
3
|
+
if (!window.__mluActions) {
|
|
4
|
+
window.__mluActions = true;
|
|
5
|
+
|
|
6
|
+
const send = (element, action, silent = false) =>
|
|
7
|
+
element.dispatchEvent(new CustomEvent("mlu-action", { bubbles: true, detail: { action, silent } }));
|
|
8
|
+
|
|
9
|
+
// value of each m-oninput field when focused or last sent, so that each edit is sent once
|
|
10
|
+
const sent = new WeakMap();
|
|
11
|
+
const save = (field) => {
|
|
12
|
+
const action = field?.getAttribute?.("m-oninput");
|
|
13
|
+
if (!action || sent.get(field) === field.value) return;
|
|
14
|
+
sent.set(field, field.value);
|
|
15
|
+
send(field, `${action}?${field.value}`, true);
|
|
16
|
+
};
|
|
17
|
+
// pressing Enter clicks or submits a form while the edited field still has focus
|
|
18
|
+
const sendAfterSave = (element, action) => {
|
|
19
|
+
save(document.activeElement);
|
|
20
|
+
send(element, action);
|
|
21
|
+
};
|
|
22
|
+
const isListed = (field) => !field.list || [...field.list.options].some((option) => option.value === field.value);
|
|
23
|
+
|
|
24
|
+
document.addEventListener("focusin", ({ target }) => {
|
|
25
|
+
if (target.hasAttribute?.("m-oninput")) sent.set(target, target.value);
|
|
26
|
+
});
|
|
27
|
+
document.addEventListener("focusout", ({ target }) => save(target));
|
|
28
|
+
|
|
29
|
+
document.addEventListener("click", (event) => {
|
|
30
|
+
const element = event.target.closest?.("[m-onclick]");
|
|
31
|
+
if (!element || element.matches(":disabled")) return;
|
|
32
|
+
event.preventDefault();
|
|
33
|
+
sendAfterSave(element, element.getAttribute("m-onclick"));
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
document.addEventListener("submit", (event) => {
|
|
37
|
+
const action = event.target.getAttribute?.("m-onsubmit");
|
|
38
|
+
if (!action) return;
|
|
39
|
+
event.preventDefault();
|
|
40
|
+
sendAfterSave(event.target, action);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
document.addEventListener("change", ({ target }) => {
|
|
44
|
+
const action = target.getAttribute?.("m-onchange");
|
|
45
|
+
// a field with a datalist changes on any edit: only listed values count, typed ones go through m-oninput
|
|
46
|
+
if (action && (!target.hasAttribute("m-oninput") || isListed(target))) send(target, `${action}?${target.value}`);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
document.addEventListener("dragstart", (event) => {
|
|
50
|
+
const element = event.target.closest?.("[m-ondragstart]");
|
|
51
|
+
if (!element) return;
|
|
52
|
+
const action = element.getAttribute("m-ondragstart");
|
|
53
|
+
event.dataTransfer.setData("text/plain", action); // Firefox only starts drags carrying data
|
|
54
|
+
event.dataTransfer.effectAllowed = "move";
|
|
55
|
+
send(element, action, true);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
document.addEventListener("drop", (event) => {
|
|
59
|
+
const element = event.target.closest?.("[m-ondrop]");
|
|
60
|
+
if (!element) return;
|
|
61
|
+
event.preventDefault();
|
|
62
|
+
send(element, element.getAttribute("m-ondrop"));
|
|
63
|
+
});
|
|
64
|
+
}
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
datamuo/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: datamuo
|
|
3
|
+
Version: 1.1.24
|
|
4
|
+
Summary: Data tensors, interactive (pivot) tables.
|
|
5
|
+
License: Copyright (c) 2025 Andrea Muolo
|
|
6
|
+
|
|
7
|
+
This software is licensed under the terms of this agreement. By using this software, you agree to the following terms:
|
|
8
|
+
|
|
9
|
+
1. Ownership: The software and all associated intellectual property rights are owned by Andrea Muolo.
|
|
10
|
+
You are granted a non-exclusive, non-transferable, revocable license to use the software.
|
|
11
|
+
|
|
12
|
+
2. Restrictions: You may not:
|
|
13
|
+
a. Reverse engineer, decompile, or disassemble the software.
|
|
14
|
+
b. Modify, adapt, or create derivative works based on the software.
|
|
15
|
+
c. Redistribute, sublicense, or transfer the software to any third party.
|
|
16
|
+
|
|
17
|
+
3. Termination: This license will terminate automatically if you fail to comply with any of the terms.
|
|
18
|
+
Upon termination, you must cease all use of the software and destroy all copies.
|
|
19
|
+
|
|
20
|
+
4. The software is provided "as is" without warranty of any kind, express or implied,
|
|
21
|
+
including but not limited to the warranties of mechantability, fitness for a particular purpose
|
|
22
|
+
and noninfringment. In no event shall the owner or the author or the copyright holder be liable for any claim,
|
|
23
|
+
damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection
|
|
24
|
+
with the software or the use or other dealings in the software.
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
License-File: LICENSE.txt
|
|
28
|
+
Classifier: License :: Other/Proprietary License
|
|
29
|
+
Classifier: Programming Language :: Python :: 3
|
|
30
|
+
Classifier: Typing :: Typed
|
|
31
|
+
Requires-Python: >=3.12
|
|
32
|
+
Requires-Dist: pythonnet<4,>=3.0.3
|
|
33
|
+
Description-Content-Type: text/markdown
|
|
34
|
+
|
|
35
|
+
# datamuo
|
|
36
|
+
|
|
37
|
+
Data tensors from plain records, interactive tables and pivot tables as HTML, and comments on data points.
|
|
38
|
+
|
|
39
|
+
## Install
|
|
40
|
+
|
|
41
|
+
Requires Python 3.12+ and the ASP.NET Core Runtime 10
|
|
42
|
+
(`dotnet --list-runtimes` lists `Microsoft.AspNetCore.App 10.x`; the SDK is not needed).
|
|
43
|
+
The package bundles the [Muoland.Reporting](https://www.nuget.org/packages/Muoland.Reporting)
|
|
44
|
+
assemblies of its version.
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pip install datamuo
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Usage
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from datamuo import Tensor
|
|
54
|
+
|
|
55
|
+
systems = Tensor("System", records) # records: mappings; dimensions default to ("id",), values to the other properties
|
|
56
|
+
roadmap = Tensor("RoadmapItem", items, dimensions=["id", "status"], aggregations={"end_date": max})
|
|
57
|
+
|
|
58
|
+
# options: order, hidden, page_size, height, width, cell_width, table_style, theme, centered
|
|
59
|
+
table = systems.table(order=["name", "owner"], page_size=50, height="65vh")
|
|
60
|
+
pivot = roadmap.pivot(rows=["id"], columns=["status"], theme="minimalist")
|
|
61
|
+
|
|
62
|
+
fragments = table.render() # Fragments(main, filter, comments, dialogs, view, slice) as HTML
|
|
63
|
+
fragments = table.render(action) # after a user interaction, see below
|
|
64
|
+
|
|
65
|
+
systems.add_comment(record, "Owner missing", author="validator", priority=1) # lower priorities are more critical
|
|
66
|
+
systems.comments(record) # history, oldest first: [Comment(tag, author, text, priority, created, view)]
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`None`, NaN and infinite values become `""`, and engine failures raise `ReportingError`. Tensors are thread-safe and shared by all users, while a report keeps its user's UI state (paging, filters, open dialogs), so web apps keep one per session, stored as they see fit:
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
from datamuo import Assets, Fragments, Report, assets
|
|
73
|
+
|
|
74
|
+
reports: dict[tuple[str, str], Report] = {}
|
|
75
|
+
|
|
76
|
+
@app.post("/reports/{name}")
|
|
77
|
+
def render(name: str, session: str, action: str = "") -> Fragments:
|
|
78
|
+
if (session, name) not in reports:
|
|
79
|
+
reports[session, name] = tensors[name].table()
|
|
80
|
+
return reports[session, name].render(action)
|
|
81
|
+
|
|
82
|
+
@app.get("/reports/assets")
|
|
83
|
+
def report_assets() -> Assets:
|
|
84
|
+
return assets()
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### Data entry, custom views and persistence
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
from datamuo import Comment, DimensionMember, Record, Report, Tensor, UiTreeBuilder, View, deserialize
|
|
91
|
+
|
|
92
|
+
def badge(ui: UiTreeBuilder, status: str) -> None: # draws each cell of a property; markup is inserted as is
|
|
93
|
+
ui.open_element("b")
|
|
94
|
+
ui.add_attribute("class", "badge")
|
|
95
|
+
ui.add_markup_content(html.escape(status))
|
|
96
|
+
ui.close_element()
|
|
97
|
+
|
|
98
|
+
table = systems.table(
|
|
99
|
+
editable=["name", "owner"], # all properties by default
|
|
100
|
+
validate=lambda report, record: [] if record["name"] else ["Name required"], # errors reject the edit
|
|
101
|
+
on_submit=lambda report, record: save(record), # each valid edit
|
|
102
|
+
on_row_click=lambda report, record: select(record), # replaces the record dialog
|
|
103
|
+
custom_views={"status": badge},
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
systems = Tensor(
|
|
107
|
+
"System", records,
|
|
108
|
+
dimension_data={"status": [DimensionMember("live", "Live"), DimensionMember("eol", "End of life", parent="live")]},
|
|
109
|
+
comments=load_comments(), on_comment=save_comment, # list[Comment], (Comment) -> None
|
|
110
|
+
views=load_views(), on_view=save_view, # list[View], (View) -> None
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
deserialize(json_lines) # JSON records as dicts sharing all keys, the missing ones None
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Callbacks get the report and plain Python records. `on_comment` and `on_view` also receive the comments and views users add in reports, on another thread.
|
|
117
|
+
|
|
118
|
+
## Frontend
|
|
119
|
+
|
|
120
|
+
Load `assets().css` and run `assets().js` once per page, then inject the fragments' HTML. Each user interaction with it dispatches a bubbling `mlu-action` event: send its `detail.action` to `Report.render` and apply the returned HTML unless `detail.silent`. Process a report's actions one at a time, in order.
|
|
121
|
+
|
|
122
|
+
```js
|
|
123
|
+
container.addEventListener("mlu-action", ({ detail: { action, silent } }) => queue(action, silent));
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
## Development
|
|
127
|
+
|
|
128
|
+
Copy the `lib/net10.0/*.dll` of a `dotnet pack` output into `src/datamuo/bin/`, then:
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
pip install -e python pytest playwright
|
|
132
|
+
python -m playwright install chromium # or set PLAYWRIGHT_CHANNEL=msedge to use an installed Edge
|
|
133
|
+
pytest python/tests # browser tests of actions.js skip without Playwright
|
|
134
|
+
```
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
datamuo/__init__.py,sha256=iu8QwHHraubLv950suY_QRRnQI0KeyIM1450z03yaWA,867
|
|
2
|
+
datamuo/_reports.py,sha256=TasJljH6na7gD192WdwOTlIRwugcjDHIhO3v-rvE7TE,17408
|
|
3
|
+
datamuo/_runtime.py,sha256=LN-HuLhEQzF0eeQ13IeR6bgGEj3Ehscz6TrWKYrg_Vw,2931
|
|
4
|
+
datamuo/actions.js,sha256=PZiqRvl0hx15fn8K4DkMS8ts8waLOn_QiA7qqB4Yu6M,2729
|
|
5
|
+
datamuo/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
datamuo/runtimeconfig.json,sha256=D0fGBG7wW2u9iyM2Q6sK3jKuRXrTOnLMwRNAb1AjNi4,173
|
|
7
|
+
datamuo/bin/Enterprise.DataTensor.dll,sha256=mGoEQBhF47rtHLAlwjAYsDXDhsUxyQd6-TuCoZKvW6s,102912
|
|
8
|
+
datamuo/bin/Enterprise.Fragments.dll,sha256=QhNwttjl4L_A054MmAHb5gxTKqnAcRtM7gBOavkqy9Q,295936
|
|
9
|
+
datamuo/bin/Enterprise.Reporting.dll,sha256=g-aVBx2Er0Q2YKDyi4uJxFdQRVgJHz8Tqo7Q-X_ikBM,1608192
|
|
10
|
+
datamuo/bin/Enterprise.Utils.dll,sha256=0Bn0MridcDWgXdhjsShpkC7fccxsxkLvugFvjXgUoqc,54784
|
|
11
|
+
datamuo-1.1.24.dist-info/METADATA,sha256=HkZwB6N4Wv7Lx7Ke5kfZoMIGVso4ncHxiKeIyrgmssI,6101
|
|
12
|
+
datamuo-1.1.24.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
13
|
+
datamuo-1.1.24.dist-info/licenses/LICENSE.txt,sha256=Jilss2k99wYRLtVgZ79EeCi5_8-6yWJslNTSzX6uc9o,1284
|
|
14
|
+
datamuo-1.1.24.dist-info/RECORD,,
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
Copyright (c) 2025 Andrea Muolo
|
|
2
|
+
|
|
3
|
+
This software is licensed under the terms of this agreement. By using this software, you agree to the following terms:
|
|
4
|
+
|
|
5
|
+
1. Ownership: The software and all associated intellectual property rights are owned by Andrea Muolo.
|
|
6
|
+
You are granted a non-exclusive, non-transferable, revocable license to use the software.
|
|
7
|
+
|
|
8
|
+
2. Restrictions: You may not:
|
|
9
|
+
a. Reverse engineer, decompile, or disassemble the software.
|
|
10
|
+
b. Modify, adapt, or create derivative works based on the software.
|
|
11
|
+
c. Redistribute, sublicense, or transfer the software to any third party.
|
|
12
|
+
|
|
13
|
+
3. Termination: This license will terminate automatically if you fail to comply with any of the terms.
|
|
14
|
+
Upon termination, you must cease all use of the software and destroy all copies.
|
|
15
|
+
|
|
16
|
+
4. The software is provided "as is" without warranty of any kind, express or implied,
|
|
17
|
+
including but not limited to the warranties of mechantability, fitness for a particular purpose
|
|
18
|
+
and noninfringment. In no event shall the owner or the author or the copyright holder be liable for any claim,
|
|
19
|
+
damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection
|
|
20
|
+
with the software or the use or other dealings in the software.
|
|
21
|
+
|
|
22
|
+
|