patrakit 0.1.0__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.
patrakit/__init__.py ADDED
@@ -0,0 +1,417 @@
1
+ """patrakit — Describe a report once. Save it as Word, PDF, PowerPoint or Excel."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ import json
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from pydantic import ValidationError
11
+
12
+ from patrakit.errors import (
13
+ AssetError,
14
+ FeatureNotAvailableError,
15
+ FontNotFoundError,
16
+ PatrakitError,
17
+ RenderError,
18
+ RenderResult,
19
+ RenderWarning,
20
+ ReportValidationError,
21
+ )
22
+ from patrakit.model.blocks import (
23
+ Block,
24
+ BreakBlock,
25
+ BulletListBlock,
26
+ ChartBlock,
27
+ ChartSeries,
28
+ ColumnDef,
29
+ HeadingBlock,
30
+ ImageBlock,
31
+ KPIItem,
32
+ KPIRowBlock,
33
+ TableBlock,
34
+ TextBlock,
35
+ )
36
+ from patrakit.model.report import ReportModel
37
+ from patrakit.theme import Fonts, Theme
38
+
39
+ __all__ = [
40
+ "Report",
41
+ "Heading",
42
+ "Text",
43
+ "BulletList",
44
+ "KPIRow",
45
+ "Table",
46
+ "Chart",
47
+ "Image",
48
+ "Break",
49
+ "Theme",
50
+ "Fonts",
51
+ "RenderResult",
52
+ "RenderWarning",
53
+ "PatrakitError",
54
+ "ReportValidationError",
55
+ "FontNotFoundError",
56
+ "AssetError",
57
+ "RenderError",
58
+ "FeatureNotAvailableError",
59
+ ]
60
+
61
+ __version__ = "0.1.0"
62
+
63
+
64
+ def _data_to_chart_parts(
65
+ data: Any,
66
+ x: str,
67
+ y: str | list[str],
68
+ ) -> tuple[list[str], list[ChartSeries]]:
69
+ rows = _coerce_data(data)
70
+ categories = [str(r[x]) for r in rows]
71
+ y_names = [y] if isinstance(y, str) else y
72
+ series = []
73
+ for name in y_names:
74
+ values = [r[name] for r in rows]
75
+ series.append(ChartSeries(name=name, values=values))
76
+ return categories, series
77
+
78
+
79
+ def _coerce_data(data: Any) -> list[dict[str, Any]]:
80
+ if isinstance(data, list):
81
+ return data
82
+ try:
83
+ import pandas as pd
84
+ if isinstance(data, pd.DataFrame):
85
+ return data.to_dict("records")
86
+ except ImportError:
87
+ pass
88
+ raise TypeError(f"Expected list of dicts or DataFrame, got {type(data).__name__}")
89
+
90
+
91
+ class Heading:
92
+ """A heading block."""
93
+
94
+ def __init__(self, text: str, level: int = 1):
95
+ self._block = HeadingBlock(text=text, level=level)
96
+
97
+ @property
98
+ def _model(self) -> HeadingBlock:
99
+ return self._block
100
+
101
+
102
+ class Text:
103
+ """A text block. A blank line starts a new paragraph."""
104
+
105
+ def __init__(self, text: str):
106
+ self._block = TextBlock(text=text)
107
+
108
+ @property
109
+ def _model(self) -> TextBlock:
110
+ return self._block
111
+
112
+
113
+ class BulletList:
114
+ """A bullet list block."""
115
+
116
+ def __init__(self, items: list[str]):
117
+ self._block = BulletListBlock(items=items)
118
+
119
+ @property
120
+ def _model(self) -> BulletListBlock:
121
+ return self._block
122
+
123
+
124
+ class KPIRow:
125
+ """A row of key performance indicators."""
126
+
127
+ def __init__(self, mapping: dict[str, str]):
128
+ items = [KPIItem(label=k, value=str(v)) for k, v in mapping.items()]
129
+ self._block = KPIRowBlock(items=items)
130
+
131
+ @property
132
+ def _model(self) -> KPIRowBlock:
133
+ return self._block
134
+
135
+
136
+ class Table:
137
+ """A data table block."""
138
+
139
+ def __init__(
140
+ self,
141
+ data: Any,
142
+ columns: list[dict[str, str]] | None = None,
143
+ formats: dict[str, str] | None = None,
144
+ ):
145
+ rows = _coerce_data(data)
146
+ col_defs = None
147
+ if columns:
148
+ col_defs = [ColumnDef(**c) for c in columns]
149
+ elif formats:
150
+ keys = list(rows[0].keys()) if rows else []
151
+ from patrakit.formats import humanize_key
152
+ col_defs = [
153
+ ColumnDef(key=k, label=humanize_key(k), format=formats.get(k, "text"))
154
+ for k in keys
155
+ ]
156
+ self._block = TableBlock(columns=col_defs, rows=rows)
157
+
158
+ @property
159
+ def _model(self) -> TableBlock:
160
+ return self._block
161
+
162
+
163
+ class Chart:
164
+ """Chart factory with static methods for bar, line, and pie charts."""
165
+
166
+ @staticmethod
167
+ def bar(
168
+ data: Any,
169
+ x: str,
170
+ y: str | list[str],
171
+ title: str | None = None,
172
+ alt_text: str | None = None,
173
+ ) -> "_ChartWrapper":
174
+ categories, series = _data_to_chart_parts(data, x, y)
175
+ block = ChartBlock(
176
+ chart_type="bar",
177
+ categories=categories,
178
+ series=series,
179
+ title=title,
180
+ alt_text=alt_text,
181
+ )
182
+ return _ChartWrapper(block)
183
+
184
+ @staticmethod
185
+ def line(
186
+ data: Any,
187
+ x: str,
188
+ y: str | list[str],
189
+ title: str | None = None,
190
+ alt_text: str | None = None,
191
+ ) -> "_ChartWrapper":
192
+ categories, series = _data_to_chart_parts(data, x, y)
193
+ block = ChartBlock(
194
+ chart_type="line",
195
+ categories=categories,
196
+ series=series,
197
+ title=title,
198
+ alt_text=alt_text,
199
+ )
200
+ return _ChartWrapper(block)
201
+
202
+ @staticmethod
203
+ def pie(
204
+ data: Any,
205
+ x: str,
206
+ y: str,
207
+ title: str | None = None,
208
+ alt_text: str | None = None,
209
+ ) -> "_ChartWrapper":
210
+ categories, series = _data_to_chart_parts(data, x, y)
211
+ block = ChartBlock(
212
+ chart_type="pie",
213
+ categories=categories,
214
+ series=series,
215
+ title=title,
216
+ alt_text=alt_text,
217
+ )
218
+ return _ChartWrapper(block)
219
+
220
+
221
+ class _ChartWrapper:
222
+ def __init__(self, block: ChartBlock):
223
+ self._block = block
224
+
225
+ @property
226
+ def _model(self) -> ChartBlock:
227
+ return self._block
228
+
229
+
230
+ class Image:
231
+ """An image block."""
232
+
233
+ def __init__(
234
+ self,
235
+ path: str,
236
+ alt_text: str | None = None,
237
+ caption: str | None = None,
238
+ width: float | None = None,
239
+ ):
240
+ self._block = ImageBlock(path=path, alt_text=alt_text, caption=caption, width=width)
241
+
242
+ @property
243
+ def _model(self) -> ImageBlock:
244
+ return self._block
245
+
246
+
247
+ class Break:
248
+ """A page or slide break."""
249
+
250
+ def __init__(self):
251
+ self._block = BreakBlock()
252
+
253
+ @property
254
+ def _model(self) -> BreakBlock:
255
+ return self._block
256
+
257
+
258
+ class Report:
259
+ """A report that can be saved to Word, PDF, PowerPoint or Excel."""
260
+
261
+ def __init__(
262
+ self,
263
+ title: str,
264
+ blocks: list[Any] | None = None,
265
+ subtitle: str | None = None,
266
+ theme: str | Theme = "modern",
267
+ asset_root: str | Path | None = None,
268
+ ):
269
+ self._title = title
270
+ self._subtitle = subtitle
271
+ self._raw_blocks = blocks or []
272
+ self._theme_input = theme
273
+ self._asset_root = Path(asset_root) if asset_root else Path.cwd()
274
+
275
+ @staticmethod
276
+ def from_json(data: str | dict[str, Any], asset_root: str | Path | None = None) -> "Report":
277
+ if isinstance(data, str):
278
+ parsed = json.loads(data)
279
+ else:
280
+ parsed = data
281
+
282
+ from patrakit.security import validate_report_limits
283
+ json_size = len(json.dumps(parsed)) if isinstance(data, str) else len(json.dumps(parsed))
284
+ validate_report_limits(len(parsed.get("blocks", [])), json_size)
285
+
286
+ try:
287
+ model = ReportModel.model_validate(parsed)
288
+ except ValidationError as e:
289
+ raise ReportValidationError(str(e)) from e
290
+
291
+ report = Report.__new__(Report)
292
+ report._title = model.title
293
+ report._subtitle = model.subtitle
294
+ report._raw_blocks = []
295
+ report._asset_root = Path(asset_root) if asset_root else Path.cwd()
296
+
297
+ from patrakit.model.report import ThemeObject
298
+ if isinstance(model.theme, str):
299
+ report._theme_input = model.theme
300
+ elif isinstance(model.theme, ThemeObject):
301
+ fonts_obj = None
302
+ if model.theme.fonts:
303
+ fonts_obj = Fonts(
304
+ family=model.theme.fonts.family,
305
+ heading=model.theme.fonts.heading,
306
+ body=model.theme.fonts.body,
307
+ table=model.theme.fonts.table,
308
+ code=model.theme.fonts.code,
309
+ fallback=model.theme.fonts.fallback,
310
+ )
311
+ report._theme_input = Theme(
312
+ base=model.theme.base,
313
+ fonts=fonts_obj,
314
+ colors={k: v for k, v in {
315
+ "primary": model.theme.colors.primary if model.theme.colors else None,
316
+ "accent": model.theme.colors.accent if model.theme.colors else None,
317
+ "text": model.theme.colors.text if model.theme.colors else None,
318
+ }.items() if v is not None} if model.theme.colors else None,
319
+ logo=model.theme.logo,
320
+ header=model.theme.header,
321
+ footer=model.theme.footer,
322
+ )
323
+ else:
324
+ report._theme_input = "modern"
325
+
326
+ report._json_blocks = model.blocks
327
+ return report
328
+
329
+ @staticmethod
330
+ def from_file(path: str | Path) -> "Report":
331
+ path = Path(path)
332
+ text = path.read_text(encoding="utf-8")
333
+ return Report.from_json(text, asset_root=path.parent)
334
+
335
+ def to_dict(self) -> dict[str, Any]:
336
+ blocks_data = []
337
+ for b in self._get_block_models():
338
+ blocks_data.append(b.model_dump(mode="json"))
339
+ return {
340
+ "schema_version": "1.0",
341
+ "title": self._title,
342
+ "subtitle": self._subtitle,
343
+ "theme": self._theme_input if isinstance(self._theme_input, str) else "modern",
344
+ "blocks": blocks_data,
345
+ }
346
+
347
+ def save(
348
+ self,
349
+ path: str | Path,
350
+ *,
351
+ strict_fonts: bool = False,
352
+ template: Any = None,
353
+ layout: str | None = None,
354
+ llm_config: Any = None,
355
+ llm_profile: str | None = None,
356
+ ) -> RenderResult:
357
+ from patrakit.security import validate_output_extension
358
+ path = Path(path)
359
+ ext = validate_output_extension(path)
360
+
361
+ if template is not None:
362
+ raise FeatureNotAvailableError("template")
363
+ if layout == "ai":
364
+ raise FeatureNotAvailableError("AI layout")
365
+ if layout is not None and layout != "ai":
366
+ raise ReportValidationError(f"Unknown layout: '{layout}'. Only 'ai' is supported (Pro feature).")
367
+ if llm_config is not None or llm_profile is not None:
368
+ if layout != "ai":
369
+ raise ReportValidationError("llm_config and llm_profile require layout='ai'")
370
+
371
+ theme_config = self._resolve_theme()
372
+ block_models = self._get_block_models()
373
+ block_ids = [f"b{i + 1}" for i in range(len(block_models))]
374
+
375
+ path.parent.mkdir(parents=True, exist_ok=True)
376
+
377
+ from patrakit.renderers import render
378
+ return render(
379
+ title=self._title,
380
+ subtitle=self._subtitle,
381
+ blocks=block_models,
382
+ output_path=path,
383
+ theme=theme_config,
384
+ asset_root=self._asset_root,
385
+ strict_fonts=strict_fonts,
386
+ block_ids=block_ids,
387
+ )
388
+
389
+ def _resolve_theme(self):
390
+ from patrakit.theme import BUILTIN_THEMES, ThemeConfig
391
+ if isinstance(self._theme_input, Theme):
392
+ return self._theme_input.config
393
+ if isinstance(self._theme_input, str):
394
+ if self._theme_input in BUILTIN_THEMES:
395
+ return copy.deepcopy(BUILTIN_THEMES[self._theme_input])
396
+ raise ReportValidationError(
397
+ f"Unknown theme '{self._theme_input}'. "
398
+ f"Available: {', '.join(BUILTIN_THEMES)}. "
399
+ "Or use Theme.load('path/to/theme.yaml')."
400
+ )
401
+ return copy.deepcopy(BUILTIN_THEMES["modern"])
402
+
403
+ def _get_block_models(self) -> list[Block]:
404
+ if hasattr(self, "_json_blocks"):
405
+ return list(self._json_blocks)
406
+ models = []
407
+ for b in self._raw_blocks:
408
+ if hasattr(b, "_model"):
409
+ models.append(b._model)
410
+ elif hasattr(b, "_block"):
411
+ models.append(b._block)
412
+ elif isinstance(b, (HeadingBlock, TextBlock, BulletListBlock, KPIRowBlock,
413
+ TableBlock, ChartBlock, ImageBlock, BreakBlock)):
414
+ models.append(b)
415
+ else:
416
+ raise ReportValidationError(f"Unknown block type: {type(b).__name__}")
417
+ return models
@@ -0,0 +1,144 @@
1
+ """Chart rendering with matplotlib."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import tempfile
7
+ from pathlib import Path
8
+ from typing import TYPE_CHECKING
9
+
10
+ import matplotlib
11
+ matplotlib.use("Agg")
12
+
13
+ import matplotlib.pyplot as plt
14
+ from matplotlib.figure import Figure
15
+
16
+ from patrakit.model.blocks import ChartBlock
17
+ from patrakit.theme import ThemeConfig
18
+
19
+ if TYPE_CHECKING:
20
+ pass
21
+
22
+
23
+ def _apply_theme(fig: Figure, ax: plt.Axes, theme: ThemeConfig) -> None:
24
+ fig.patch.set_facecolor("white")
25
+ ax.set_facecolor("white")
26
+ ax.tick_params(colors=theme.colors.text)
27
+ ax.xaxis.label.set_color(theme.colors.text)
28
+ ax.yaxis.label.set_color(theme.colors.text)
29
+ for spine in ax.spines.values():
30
+ spine.set_color("#CCCCCC")
31
+
32
+
33
+ def render_chart_to_png(block: ChartBlock, theme: ThemeConfig, dpi: int = 200) -> bytes:
34
+ fig, ax = plt.subplots(figsize=(6, 4))
35
+ _apply_theme(fig, ax, theme)
36
+ _draw_chart(ax, block, theme)
37
+ if block.title:
38
+ ax.set_title(block.title, color=theme.colors.text, fontsize=12, fontweight="bold")
39
+ fig.tight_layout()
40
+ buf = io.BytesIO()
41
+ fig.savefig(buf, format="png", dpi=dpi, bbox_inches="tight", facecolor="white")
42
+ plt.close(fig)
43
+ buf.seek(0)
44
+ return buf.read()
45
+
46
+
47
+ def render_chart_to_svg(block: ChartBlock, theme: ThemeConfig) -> str:
48
+ old_fonttype = matplotlib.rcParams.get("svg.fonttype")
49
+ try:
50
+ matplotlib.rcParams["svg.fonttype"] = "path"
51
+ fig, ax = plt.subplots(figsize=(6, 4))
52
+ _apply_theme(fig, ax, theme)
53
+ _draw_chart(ax, block, theme)
54
+ if block.title:
55
+ ax.set_title(block.title, color=theme.colors.text, fontsize=12, fontweight="bold")
56
+ fig.tight_layout()
57
+ buf = io.StringIO()
58
+ fig.savefig(buf, format="svg", bbox_inches="tight", facecolor="white")
59
+ plt.close(fig)
60
+ return buf.getvalue()
61
+ finally:
62
+ if old_fonttype is not None:
63
+ matplotlib.rcParams["svg.fonttype"] = old_fonttype
64
+
65
+
66
+ def save_chart_png(block: ChartBlock, theme: ThemeConfig, path: Path, dpi: int = 200) -> Path:
67
+ data = render_chart_to_png(block, theme, dpi)
68
+ path.parent.mkdir(parents=True, exist_ok=True)
69
+ path.write_bytes(data)
70
+ return path
71
+
72
+
73
+ def save_chart_svg(block: ChartBlock, theme: ThemeConfig, path: Path) -> Path:
74
+ svg = render_chart_to_svg(block, theme)
75
+ path.parent.mkdir(parents=True, exist_ok=True)
76
+ path.write_text(svg, encoding="utf-8")
77
+ return path
78
+
79
+
80
+ def _draw_chart(ax: plt.Axes, block: ChartBlock, theme: ThemeConfig) -> None:
81
+ if block.chart_type == "bar":
82
+ _draw_bar(ax, block, theme)
83
+ elif block.chart_type == "line":
84
+ _draw_line(ax, block, theme)
85
+ elif block.chart_type == "pie":
86
+ _draw_pie(ax, block, theme)
87
+
88
+
89
+ def _get_colors(theme: ThemeConfig, count: int) -> list[str]:
90
+ base_colors = [
91
+ theme.colors.primary,
92
+ theme.colors.accent,
93
+ "#4CAF50",
94
+ "#9C27B0",
95
+ "#FF9800",
96
+ "#00BCD4",
97
+ "#795548",
98
+ "#607D8B",
99
+ ]
100
+ colors = []
101
+ for i in range(count):
102
+ colors.append(base_colors[i % len(base_colors)])
103
+ return colors
104
+
105
+
106
+ def _draw_bar(ax: plt.Axes, block: ChartBlock, theme: ThemeConfig) -> None:
107
+ import numpy as np
108
+
109
+ x = np.arange(len(block.categories))
110
+ n_series = len(block.series)
111
+ width = 0.8 / n_series
112
+ colors = _get_colors(theme, n_series)
113
+
114
+ for i, series in enumerate(block.series):
115
+ offset = (i - n_series / 2 + 0.5) * width
116
+ bars = ax.bar(x + offset, series.values, width, label=series.name, color=colors[i])
117
+
118
+ ax.set_xticks(x)
119
+ ax.set_xticklabels(block.categories, rotation=45 if len(block.categories) > 6 else 0, ha="right" if len(block.categories) > 6 else "center")
120
+ if n_series > 1:
121
+ ax.legend()
122
+
123
+
124
+ def _draw_line(ax: plt.Axes, block: ChartBlock, theme: ThemeConfig) -> None:
125
+ colors = _get_colors(theme, len(block.series))
126
+ for i, series in enumerate(block.series):
127
+ ax.plot(block.categories, series.values, marker="o", label=series.name, color=colors[i], linewidth=2)
128
+ if len(block.series) > 1:
129
+ ax.legend()
130
+ if len(block.categories) > 6:
131
+ ax.tick_params(axis="x", rotation=45)
132
+
133
+
134
+ def _draw_pie(ax: plt.Axes, block: ChartBlock, theme: ThemeConfig) -> None:
135
+ series = block.series[0]
136
+ colors = _get_colors(theme, len(block.categories))
137
+ ax.pie(
138
+ series.values,
139
+ labels=block.categories,
140
+ colors=colors,
141
+ autopct="%1.1f%%",
142
+ startangle=90,
143
+ )
144
+ ax.set_aspect("equal")