stplot 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.
Files changed (49) hide show
  1. stplot/__init__.py +21 -0
  2. stplot/config/__init__.py +33 -0
  3. stplot/config/loader.py +106 -0
  4. stplot/config/models.py +328 -0
  5. stplot/config/presets/__init__.py +1 -0
  6. stplot/config/presets/default.yaml +208 -0
  7. stplot/config/presets/horizons_one_plan.yaml +59 -0
  8. stplot/io/__init__.py +6 -0
  9. stplot/io/spatial.py +72 -0
  10. stplot/io/tabular.py +154 -0
  11. stplot/plots/__init__.py +122 -0
  12. stplot/plots/barbell.py +400 -0
  13. stplot/plots/batch.py +135 -0
  14. stplot/plots/domains.py +1143 -0
  15. stplot/plots/executive.py +474 -0
  16. stplot/plots/export.py +74 -0
  17. stplot/plots/infographics.py +1118 -0
  18. stplot/plots/lollipop.py +285 -0
  19. stplot/plots/maps.py +738 -0
  20. stplot/plots/matrix.py +190 -0
  21. stplot/plots/one_plan.py +642 -0
  22. stplot/plots/paired.py +437 -0
  23. stplot/plots/scorecards.py +1940 -0
  24. stplot/plots/state.py +373 -0
  25. stplot/plots/state_trends.py +1413 -0
  26. stplot/plots/tables.py +107 -0
  27. stplot/plots/timeseries.py +607 -0
  28. stplot/plots/trends.py +305 -0
  29. stplot/reporting/__init__.py +24 -0
  30. stplot/reporting/captions.py +177 -0
  31. stplot/reporting/html_companion.py +339 -0
  32. stplot/reporting/templates.py +485 -0
  33. stplot/reporting/word.py +369 -0
  34. stplot/theme/__init__.py +25 -0
  35. stplot/theme/folium.py +62 -0
  36. stplot/theme/mpl.py +181 -0
  37. stplot/theme/plotly.py +130 -0
  38. stplot/transform/__init__.py +60 -0
  39. stplot/transform/categories.py +51 -0
  40. stplot/transform/columns.py +103 -0
  41. stplot/transform/filters.py +385 -0
  42. stplot/transform/merge.py +173 -0
  43. stplot/transform/pairing.py +154 -0
  44. stplot/transform/qa.py +297 -0
  45. stplot/transform/tables.py +573 -0
  46. stplot/transform/zones.py +354 -0
  47. stplot-0.1.0.dist-info/METADATA +235 -0
  48. stplot-0.1.0.dist-info/RECORD +49 -0
  49. stplot-0.1.0.dist-info/WHEEL +4 -0
@@ -0,0 +1,339 @@
1
+ """Self-contained interactive HTML Companion Pack builder for regional & FMU reporting."""
2
+ # ruff: noqa: E501
3
+
4
+ from __future__ import annotations
5
+
6
+ import base64
7
+ import html
8
+ import re
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import pandas as pd
13
+
14
+ from stplot.config import Config, ensure_config
15
+
16
+
17
+ def _slug(text: str) -> str:
18
+ cleaned = re.sub(r"[^a-zA-Z0-9]+", "-", text.strip().lower()).strip("-")
19
+ return cleaned or "section"
20
+
21
+
22
+ def _encode_image_data_uri(path: Path) -> str:
23
+ suffix = path.suffix.lower().lstrip(".")
24
+ mime = {
25
+ "png": "image/png",
26
+ "jpg": "image/jpeg",
27
+ "jpeg": "image/jpeg",
28
+ "svg": "image/svg+xml",
29
+ "webp": "image/webp",
30
+ }.get(suffix, "image/png")
31
+ b64 = base64.b64encode(path.read_bytes()).decode("ascii")
32
+ return f"data:{mime};base64,{b64}"
33
+
34
+
35
+ def _render_item_html(item: dict[str, Any], *, plotly_js_included: list[bool]) -> str:
36
+ kind = str(item.get("type", "")).strip().lower()
37
+ title = html.escape(str(item.get("title", "")))
38
+ caption = html.escape(str(item.get("caption", "")))
39
+ title_html = f'<h3 class="card-title">{title}</h3>' if title else ""
40
+ cap_html = f'<p class="card-caption">{caption}</p>' if caption else ""
41
+
42
+ if kind == "image" or (not kind and "path" in item):
43
+ img_path = Path(item["path"])
44
+ if not img_path.exists():
45
+ raise FileNotFoundError(f"build_html_companion: Image not found: {img_path}")
46
+ uri = _encode_image_data_uri(img_path)
47
+ alt = title or img_path.stem
48
+ return (
49
+ f'<div class="card">{title_html}'
50
+ f'<div class="img-wrap"><img src="{uri}" alt="{alt}" /></div>'
51
+ f"{cap_html}</div>"
52
+ )
53
+
54
+ if kind == "plotly":
55
+ fig = item.get("figure")
56
+ if fig is not None and hasattr(fig, "to_html"):
57
+ include_js: str | bool = "cdn" if not plotly_js_included[0] else False
58
+ plotly_js_included[0] = True
59
+ div_html = fig.to_html(full_html=False, include_plotlyjs=include_js)
60
+ return f'<div class="card">{title_html}<div class="plotly-wrap">{div_html}</div>{cap_html}</div>'
61
+ if "path" in item:
62
+ raw = Path(item["path"]).read_text(encoding="utf-8")
63
+ esc = html.escape(raw, quote=True)
64
+ height = int(item.get("height", 520))
65
+ return (
66
+ f'<div class="card">{title_html}'
67
+ f'<iframe class="embed-frame" style="height:{height}px;" srcdoc="{esc}"></iframe>'
68
+ f"{cap_html}</div>"
69
+ )
70
+ raise ValueError("build_html_companion: Plotly item requires 'figure' or 'path'.")
71
+
72
+ if kind == "folium":
73
+ fmap = item.get("map")
74
+ height = int(item.get("height", 520))
75
+ if fmap is not None and hasattr(fmap, "get_root"):
76
+ raw = fmap.get_root().render()
77
+ elif "path" in item:
78
+ raw = Path(item["path"]).read_text(encoding="utf-8")
79
+ else:
80
+ raise ValueError("build_html_companion: Folium item requires 'map' or 'path'.")
81
+ esc = html.escape(raw, quote=True)
82
+ return (
83
+ f'<div class="card">{title_html}'
84
+ f'<iframe class="embed-frame" style="height:{height}px;" srcdoc="{esc}"></iframe>'
85
+ f"{cap_html}</div>"
86
+ )
87
+
88
+ if kind == "table":
89
+ df = item.get("df")
90
+ if not isinstance(df, pd.DataFrame):
91
+ raise ValueError(
92
+ "build_html_companion: Table item requires a pandas DataFrame in 'df'."
93
+ )
94
+ tbl_html = df.to_html(
95
+ index=bool(item.get("show_index", False)), classes="data-table", border=0
96
+ )
97
+ return f'<div class="card">{title_html}<div class="table-wrap">{tbl_html}</div>{cap_html}</div>'
98
+
99
+ if kind == "callout":
100
+ tone = str(item.get("tone", "info")).lower()
101
+ tone_cls = tone if tone in {"info", "warn", "good"} else "info"
102
+ body_parts: list[str] = []
103
+ if item.get("text"):
104
+ body_parts.append(f"<p>{html.escape(str(item['text']))}</p>")
105
+ if item.get("bullets"):
106
+ lis = "".join(f"<li>{html.escape(str(b))}</li>" for b in item["bullets"])
107
+ body_parts.append(f"<ul>{lis}</ul>")
108
+ return f'<div class="callout callout-{tone_cls}">{title_html}{"".join(body_parts)}</div>'
109
+
110
+ raise ValueError(
111
+ f"build_html_companion: Unsupported item type '{kind}'. "
112
+ "Supported types: 'image', 'plotly', 'folium', 'table', 'callout'."
113
+ )
114
+
115
+
116
+ def build_html_companion(
117
+ output_path: str | Path,
118
+ *,
119
+ title: str,
120
+ sections: list[dict[str, Any]],
121
+ subtitle: str | None = None,
122
+ region_name: str | None = None,
123
+ reporting_period: str | None = None,
124
+ author: str | None = None,
125
+ kpis: list[dict[str, Any]] | None = None,
126
+ config: str | Path | Config | None = None,
127
+ ) -> Path:
128
+ """Build a self-contained, tabbed interactive HTML Companion Pack for a report.
129
+
130
+ Bundles static PNG/SVG figures (base64-inlined), interactive ``plotly`` charts,
131
+ interactive ``folium`` maps, styled ``pandas`` tables, and QA callout cards into
132
+ a single shareable HTML file with tab navigation by Region / FMU / QA.
133
+
134
+ Args:
135
+ output_path: Destination ``.html`` file path.
136
+ title: Main dashboard header title.
137
+ sections: List of tab section dicts, each containing:
138
+ - ``title`` (str): Tab label & section heading
139
+ - ``summary`` (str, optional): Short introductory paragraph
140
+ - ``items`` (list[dict]): Cards of type ``"image"``, ``"plotly"``,
141
+ ``"folium"``, ``"table"``, or ``"callout"``.
142
+ subtitle: Optional subtitle displayed in the header banner.
143
+ region_name: Optional region badge in header metadata.
144
+ reporting_period: Optional reporting period badge in header metadata.
145
+ author: Optional team/author credit in header & footer.
146
+ kpis: Optional list of KPI dicts (``label``, ``value``, optional ``delta``).
147
+ config: Optional Config object, preset name, or path to YAML/TOML config.
148
+
149
+ Returns:
150
+ Resolved :class:`pathlib.Path` to the written ``.html`` file.
151
+ """
152
+ if not sections:
153
+ raise ValueError("build_html_companion: 'sections' cannot be empty.")
154
+
155
+ cfg = ensure_config(config)
156
+ accent = cfg.theme.accent_color
157
+ text_col = cfg.theme.text_color
158
+ out_path = Path(output_path)
159
+ out_path.parent.mkdir(parents=True, exist_ok=True)
160
+
161
+ meta_bits = [b for b in (region_name, reporting_period, author) if b]
162
+ meta_html = (
163
+ '<div class="meta-row">'
164
+ + "".join(f'<span class="meta-pill">{html.escape(str(b))}</span>' for b in meta_bits)
165
+ + "</div>"
166
+ if meta_bits
167
+ else ""
168
+ )
169
+
170
+ kpi_html = ""
171
+ if kpis:
172
+ cards = []
173
+ for k in kpis:
174
+ lbl = html.escape(str(k.get("label", "")))
175
+ val = html.escape(str(k.get("value", "")))
176
+ delta = html.escape(str(k.get("delta", "")))
177
+ d_html = f'<div class="kpi-delta">{delta}</div>' if delta else ""
178
+ cards.append(
179
+ f'<div class="kpi-card"><div class="kpi-val">{val}</div>'
180
+ f'<div class="kpi-lbl">{lbl}</div>{d_html}</div>'
181
+ )
182
+ kpi_html = f'<div class="kpi-grid">{"".join(cards)}</div>'
183
+
184
+ plotly_js_included = [False]
185
+ tab_buttons: list[str] = []
186
+ tab_panels: list[str] = []
187
+
188
+ for idx, sec in enumerate(sections):
189
+ sec_title = str(sec.get("title", f"Section {idx + 1}"))
190
+ sec_id = f"tab-{idx}-{_slug(sec_title)}"
191
+ active_cls = " active" if idx == 0 else ""
192
+ tab_buttons.append(
193
+ f'<button class="tab-btn{active_cls}" data-tab="{sec_id}">'
194
+ f"{html.escape(sec_title)}</button>"
195
+ )
196
+ sec_sum = (
197
+ f'<p class="sec-summary">{html.escape(str(sec["summary"]))}</p>'
198
+ if sec.get("summary")
199
+ else ""
200
+ )
201
+ items_html = "\n".join(
202
+ _render_item_html(it, plotly_js_included=plotly_js_included)
203
+ for it in sec.get("items", [])
204
+ )
205
+ tab_panels.append(
206
+ f'<section id="{sec_id}" class="tab-panel{active_cls}">'
207
+ f'<h2 class="sec-title">{html.escape(sec_title)}</h2>'
208
+ f"{sec_sum}{items_html}</section>"
209
+ )
210
+
211
+ sub_html = f'<p class="hero-sub">{html.escape(subtitle)}</p>' if subtitle else ""
212
+ footer_txt = html.escape(f"Generated with stplot — {author or 'Environmental Reporting'}")
213
+
214
+ page = f"""<!DOCTYPE html>
215
+ <html lang="en">
216
+ <head>
217
+ <meta charset="utf-8" />
218
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
219
+ <title>{html.escape(title)}</title>
220
+ <style>
221
+ :root {{
222
+ --accent: {accent};
223
+ --text: {text_col};
224
+ --muted: #5b6875;
225
+ --bg: #f4f6f9;
226
+ --card: #ffffff;
227
+ --border: #dce3ec;
228
+ }}
229
+ * {{ box-sizing: border-box; }}
230
+ body {{
231
+ margin: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
232
+ background: var(--bg); color: var(--text); line-height: 1.5;
233
+ }}
234
+ .hero {{
235
+ background: linear-gradient(135deg, #162b44 0%, var(--accent) 100%);
236
+ color: #fff; padding: 28px 32px 24px;
237
+ }}
238
+ .hero h1 {{ margin: 0 0 6px; font-size: 1.75rem; letter-spacing: -0.01em; }}
239
+ .hero-sub {{ margin: 0 0 12px; opacity: 0.9; font-size: 1rem; }}
240
+ .meta-row {{ display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; }}
241
+ .meta-pill {{
242
+ background: rgba(255,255,255,0.16); border: 1px solid rgba(255,255,255,0.28);
243
+ padding: 3px 10px; border-radius: 999px; font-size: 0.82rem; font-weight: 600;
244
+ }}
245
+ .container {{ max-width: 1180px; margin: 0 auto; padding: 20px 24px 48px; }}
246
+ .kpi-grid {{
247
+ display: grid; grid-template-columns: repeat(auto-fit, minmax(190px, 1fr));
248
+ gap: 14px; margin-bottom: 20px;
249
+ }}
250
+ .kpi-card {{
251
+ background: var(--card); border: 1px solid var(--border); border-top: 4px solid var(--accent);
252
+ border-radius: 10px; padding: 14px 16px; box-shadow: 0 1px 3px rgba(15,23,42,0.05);
253
+ }}
254
+ .kpi-val {{ font-size: 1.65rem; font-weight: 800; color: var(--text); }}
255
+ .kpi-lbl {{ font-size: 0.85rem; color: var(--muted); font-weight: 600; margin-top: 2px; }}
256
+ .kpi-delta {{ font-size: 0.8rem; color: var(--accent); font-weight: 600; margin-top: 4px; }}
257
+ .tabs {{
258
+ display: flex; flex-wrap: wrap; gap: 8px; border-bottom: 2px solid var(--border);
259
+ padding-bottom: 10px; margin-bottom: 22px;
260
+ }}
261
+ .tab-btn {{
262
+ background: var(--card); border: 1px solid var(--border); border-radius: 8px;
263
+ padding: 8px 16px; font-size: 0.92rem; font-weight: 600; color: var(--text);
264
+ cursor: pointer; transition: all 0.15s ease;
265
+ }}
266
+ .tab-btn:hover {{ border-color: var(--accent); color: var(--accent); }}
267
+ .tab-btn.active {{ background: var(--accent); border-color: var(--accent); color: #fff; }}
268
+ .tab-panel {{ display: none; }}
269
+ .tab-panel.active {{ display: block; }}
270
+ .sec-title {{ margin: 0 0 8px; font-size: 1.35rem; }}
271
+ .sec-summary {{ margin: 0 0 18px; color: var(--muted); }}
272
+ .card {{
273
+ background: var(--card); border: 1px solid var(--border); border-radius: 12px;
274
+ padding: 18px 20px; margin-bottom: 18px; box-shadow: 0 1px 4px rgba(15,23,42,0.04);
275
+ }}
276
+ .card-title {{ margin: 0 0 12px; font-size: 1.05rem; }}
277
+ .card-caption {{ margin: 10px 0 0; font-size: 0.86rem; color: var(--muted); font-style: italic; }}
278
+ .img-wrap img {{ max-width: 100%; height: auto; display: block; margin: 0 auto; border-radius: 6px; }}
279
+ .embed-frame {{ width: 100%; border: 1px solid var(--border); border-radius: 8px; background: #fff; }}
280
+ .table-wrap {{ overflow-x: auto; }}
281
+ .data-table {{ width: 100%; border-collapse: collapse; font-size: 0.9rem; }}
282
+ .data-table th {{
283
+ background: #f1f5f9; text-align: left; padding: 9px 12px; border-bottom: 2px solid var(--border);
284
+ font-weight: 700;
285
+ }}
286
+ .data-table td {{ padding: 8px 12px; border-bottom: 1px solid #edf2f7; }}
287
+ .data-table tr:nth-child(even) td {{ background: #fafbfd; }}
288
+ .callout {{
289
+ border-radius: 10px; padding: 14px 18px; margin-bottom: 18px; border-left: 4px solid var(--accent);
290
+ background: #eef7fb;
291
+ }}
292
+ .callout-warn {{ border-left-color: #d97706; background: #fffbeb; }}
293
+ .callout-good {{ border-left-color: #2e7d32; background: #f0fdf4; }}
294
+ .callout ul {{ margin: 6px 0 0 18px; padding: 0; }}
295
+ footer {{
296
+ text-align: center; color: var(--muted); font-size: 0.82rem; padding: 18px;
297
+ border-top: 1px solid var(--border); margin-top: 24px;
298
+ }}
299
+ </style>
300
+ </head>
301
+ <body>
302
+ <header class="hero">
303
+ <div style="max-width:1180px;margin:0 auto;">
304
+ <h1>{html.escape(title)}</h1>
305
+ {sub_html}
306
+ {meta_html}
307
+ </div>
308
+ </header>
309
+ <main class="container">
310
+ {kpi_html}
311
+ <nav class="tabs" role="tablist">
312
+ {"".join(tab_buttons)}
313
+ </nav>
314
+ {"".join(tab_panels)}
315
+ </main>
316
+ <footer>{footer_txt}</footer>
317
+ <script>
318
+ document.querySelectorAll(".tab-btn").forEach(function(btn) {{
319
+ btn.addEventListener("click", function() {{
320
+ document.querySelectorAll(".tab-btn").forEach(function(b) {{ b.classList.remove("active"); }});
321
+ document.querySelectorAll(".tab-panel").forEach(function(p) {{ p.classList.remove("active"); }});
322
+ btn.classList.add("active");
323
+ var panel = document.getElementById(btn.dataset.tab);
324
+ if (panel) {{
325
+ panel.classList.add("active");
326
+ if (window.Plotly) {{
327
+ panel.querySelectorAll(".js-plotly-plot").forEach(function(gd) {{
328
+ window.Plotly.Plots.resize(gd);
329
+ }});
330
+ }}
331
+ }}
332
+ }});
333
+ }});
334
+ </script>
335
+ </body>
336
+ </html>
337
+ """
338
+ out_path.write_text(page, encoding="utf-8")
339
+ return out_path