diff --git a/.cspell/dictionary.txt b/.cspell/dictionary.txt
index 40739d4d..dab8dedf 100644
--- a/.cspell/dictionary.txt
+++ b/.cspell/dictionary.txt
@@ -183,3 +183,45 @@ Deutsch
getpid
killpg
pids
+# Figures: Graphviz, d2, librsvg, matplotlib, fontTools and SVG terms
+addfont
+autopct
+axhline
+axvline
+circo
+cmap
+counterclock
+dasharray
+dashoffset
+endset
+epsf
+figsize
+fontname
+fontnames
+fontpath
+fontsize
+fonttype
+hashsalt
+hmtx
+imagepath
+librsvg
+linecap
+linejoin
+linestyle
+miterlimit
+neato
+pctdistance
+rsvg
+startangle
+supxlabel
+textcoords
+tspan
+twopi
+wedgeprops
+xlabel
+xlink
+xticks
+xytext
+ylabel
+ylim
+yticks
diff --git a/packages/dsw-document-worker/CHANGELOG.md b/packages/dsw-document-worker/CHANGELOG.md
index 54e0d9b7..e99432ef 100644
--- a/packages/dsw-document-worker/CHANGELOG.md
+++ b/packages/dsw-document-worker/CHANGELOG.md
@@ -7,6 +7,13 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
+### Added
+
+- Figures in documents (`graphviz`, `d2`, `chart`, `svg`): `externals.graphviz`, `externals.d2` and
+ `externals.rsvg` (`executable`, `timeout`, 30 s by default; `GRAPHVIZ_*`, `D2_*`, `RSVG_*`),
+ `figures.fontDir` (`FIGURES_FONT_DIR`) and `figures.limits`; the images need `dot`, `d2` and
+ `rsvg-convert`
+
### Changed
- Document context metamodel 19.1; contexts of 19.0 are still rendered, newer minor versions are
diff --git a/packages/dsw-document-worker/config.example.yml b/packages/dsw-document-worker/config.example.yml
index 93e04108..bdf4abf3 100644
--- a/packages/dsw-document-worker/config.example.yml
+++ b/packages/dsw-document-worker/config.example.yml
@@ -61,3 +61,28 @@ templates:
# executable: pandoc
# args: --standalone
# timeout:
+# graphviz:
+# executable: dot
+# timeout: 30 # seconds, never unlimited
+# d2:
+# executable: d2
+# timeout: 30
+# rsvg:
+# executable: rsvg-convert
+# timeout: 30
+
+#figures:
+# fontDir: /usr/share/fonts/truetype/custom
+# limits: # see FigureLimits of dsw-templating
+# maxFigures: 200 # per document
+# maxRenderSeconds: 120 # per document
+# maxOutputBytes: 20971520
+# maxSourceBytes: 1048576
+# maxChartSpecBytes: 1048576
+# maxChartLabels: 1000
+# maxChartSeries: 50
+# maxChartPoints: 20000
+# maxSizePx: 5000
+# maxElements: 100000
+# maxPathLength: 100000
+# maxTextLength: 10000
diff --git a/packages/dsw-document-worker/dsw/document_worker/config.py b/packages/dsw-document-worker/dsw/document_worker/config.py
index 3f2245a9..700c7ab5 100644
--- a/packages/dsw-document-worker/dsw/document_worker/config.py
+++ b/packages/dsw-document-worker/dsw/document_worker/config.py
@@ -10,6 +10,8 @@
ConfigKeys,
ConfigKeysContainer,
cast_bool,
+ cast_dict,
+ cast_float,
cast_int,
cast_optional_int,
cast_str,
@@ -160,10 +162,46 @@ class _CommandPandocKeys(ConfigKeysContainer):
)
+def _tool_keys(name: str, env_prefix: str, executable: str) -> tuple[ConfigKey, ConfigKey]:
+ return (
+ ConfigKey(
+ yaml_path=['externals', name, 'executable'],
+ var_names=[f'{env_prefix}_EXECUTABLE'],
+ default=executable,
+ cast=cast_str,
+ ),
+ ConfigKey(
+ yaml_path=['externals', name, 'timeout'],
+ var_names=[f'{env_prefix}_TIMEOUT'],
+ default=30,
+ cast=cast_float,
+ ),
+ )
+
+
+class _FigureKeys(ConfigKeysContainer):
+ graphviz_executable, graphviz_timeout = _tool_keys('graphviz', 'GRAPHVIZ', 'dot')
+ d2_executable, d2_timeout = _tool_keys('d2', 'D2', 'd2')
+ rsvg_executable, rsvg_timeout = _tool_keys('rsvg', 'RSVG', 'rsvg-convert')
+ font_dir = ConfigKey(
+ yaml_path=['figures', 'fontDir'],
+ var_names=['FIGURES_FONT_DIR'],
+ default='/usr/share/fonts/truetype/custom',
+ cast=cast_str,
+ )
+ #: FigureLimits of dsw-templating, in camelCase
+ limits = ConfigKey(
+ yaml_path=['figures', 'limits'],
+ default={},
+ cast=cast_dict,
+ )
+
+
class DocWorkerConfigKeys(ConfigKeys):
documents = _DocumentsKeys
experimental = _ExperimentalKeys
cmd_pandoc = _CommandPandocKeys
+ figures = _FigureKeys
context = _DocumentContextKeys
security = _SecurityKeys
@@ -214,6 +252,15 @@ def command(self) -> list[str]:
return [self.executable] + shlex.split(self.args)
+@dataclasses.dataclass
+class FiguresConfig(ConfigModel):
+ graphviz: CommandConfig
+ d2: CommandConfig
+ rsvg: CommandConfig
+ font_dir: str
+ limits: dict[str, typing.Any]
+
+
@dataclasses.dataclass
class TemplateRequestsConfig:
enabled: bool
@@ -266,6 +313,7 @@ class DocumentWorkerConfig:
log: LoggingConfig
doc: DocumentsConfig
pandoc: CommandConfig
+ figures: FiguresConfig
templates: TemplatesConfig
experimental: ExperimentalConfig
cloud: CloudConfig
@@ -288,6 +336,7 @@ def __str__(self):
f'{self.context}' \
f'{self.security}' \
f'Pandoc: {self.pandoc}' \
+ f'{self.figures}' \
f'====================\n'
@@ -313,6 +362,18 @@ def pandoc(self) -> CommandConfig:
timeout=self.get(self.keys.cmd_pandoc.timeout),
)
+ @property
+ def figures(self) -> FiguresConfig:
+ keys = self.keys.figures
+ return FiguresConfig(
+ graphviz=CommandConfig(self.get(keys.graphviz_executable), '',
+ self.get(keys.graphviz_timeout)),
+ d2=CommandConfig(self.get(keys.d2_executable), '', self.get(keys.d2_timeout)),
+ rsvg=CommandConfig(self.get(keys.rsvg_executable), '', self.get(keys.rsvg_timeout)),
+ font_dir=self.get(keys.font_dir),
+ limits=self.get(keys.limits),
+ )
+
@property
def templates(self) -> TemplatesConfig:
return TemplatesConfig(
@@ -358,6 +419,7 @@ def config(self) -> DocumentWorkerConfig:
log=self.logging,
doc=self.documents,
pandoc=self.pandoc,
+ figures=self.figures,
templates=self.templates,
experimental=self.experimental,
cloud=self.cloud,
diff --git a/packages/dsw-document-worker/dsw/document_worker/templates/templates.py b/packages/dsw-document-worker/dsw/document_worker/templates/templates.py
index 9606301c..f0c1d3d3 100644
--- a/packages/dsw-document-worker/dsw/document_worker/templates/templates.py
+++ b/packages/dsw-document-worker/dsw/document_worker/templates/templates.py
@@ -8,13 +8,17 @@
import shutil
import typing
+from dsw.models.common import to_camel
from dsw.templating import (
+ FigureLimits,
+ FigureSettings,
PandocSettings,
RenderContext,
RenderSettings,
RequestsSettings,
SecuritySettings,
TemplateSettings,
+ ToolSettings,
register_plugin_steps,
)
from dsw.templating import Template as TemplateEngine
@@ -70,10 +74,28 @@ def render_settings(cfg: DocumentWorkerConfig, coordinates: str) -> RenderSettin
],
templates_dir=pathlib.Path(os.getenv('PANDOC_TEMPLATES', '/pandoc/templates')),
),
+ figures=figure_settings(cfg),
template=template_settings,
)
+def figure_settings(cfg: DocumentWorkerConfig) -> FigureSettings:
+ fields = {to_camel(field.name): field.name for field in dataclasses.fields(FigureLimits)}
+ limits: dict[str, typing.Any] = {}
+ for key, value in cfg.figures.limits.items():
+ if key not in fields:
+ raise ValueError(f'Unknown key "{key}" in figures.limits, '
+ f'use one of: {", ".join(fields)}')
+ limits[fields[key]] = value
+ return FigureSettings(
+ graphviz=ToolSettings(cfg.figures.graphviz.command, cfg.figures.graphviz.timeout),
+ d2=ToolSettings(cfg.figures.d2.command, cfg.figures.d2.timeout),
+ rsvg=ToolSettings(cfg.figures.rsvg.command, cfg.figures.rsvg.timeout),
+ limits=FigureLimits(**limits),
+ font_dir=pathlib.Path(cfg.figures.font_dir),
+ )
+
+
class S3ProjectFiles:
"""Project files of one project, downloaded from S3 into the template directory."""
diff --git a/packages/dsw-document-worker/tests/test_templating.py b/packages/dsw-document-worker/tests/test_templating.py
index 437bb4e0..afc9e922 100644
--- a/packages/dsw-document-worker/tests/test_templating.py
+++ b/packages/dsw-document-worker/tests/test_templating.py
@@ -6,6 +6,7 @@
from dsw.document_worker.config import (
CommandConfig,
+ FiguresConfig,
SecurityConfig,
TemplateConfig,
TemplateRequestsConfig,
@@ -18,7 +19,7 @@
from dsw.templating.settings import bundled_pandoc_filters
-def make_config(*templates: TemplateConfig):
+def make_config(*templates: TemplateConfig, limits: dict | None = None):
return types.SimpleNamespace(
templates=TemplatesConfig(templates=list(templates)),
security=SecurityConfig(
@@ -29,6 +30,13 @@ def make_config(*templates: TemplateConfig):
max_redirects=5,
),
pandoc=CommandConfig(executable='pandoc', args='--standalone --wrap=none', timeout=30),
+ figures=FiguresConfig(
+ graphviz=CommandConfig(executable='/opt/dot', args='', timeout=5),
+ d2=CommandConfig(executable='d2', args='', timeout=30),
+ rsvg=CommandConfig(executable='rsvg-convert', args='', timeout=30),
+ font_dir='/fonts',
+ limits=limits or {},
+ ),
)
@@ -54,6 +62,21 @@ def test_render_settings_from_config():
assert settings.template.requests.timeout == 2
+def test_figure_settings_from_config():
+ settings = render_settings(make_config(limits={'maxFigures': 3, 'maxSizePx': 800}),
+ 'org:tid:1.0.0').figures
+ assert settings.graphviz.command == ['/opt/dot'] and settings.graphviz.timeout == 5
+ assert settings.rsvg.command == ['rsvg-convert']
+ assert settings.font_dir == pathlib.Path('/fonts')
+ assert settings.limits.max_figures == 3 and settings.limits.max_size_px == 800
+ assert settings.limits.max_elements == 100_000
+
+
+def test_unknown_figure_limit_is_refused():
+ with pytest.raises(ValueError, match='Unknown key "maxFigure" in figures.limits'):
+ render_settings(make_config(limits={'maxFigure': 3}), 'org:tid:1.0.0')
+
+
def test_render_settings_without_template_config():
assert render_settings(make_config(), 'org:tid:1.0.0').template is None
diff --git a/packages/dsw-models/dsw/models/document_template/migrations.py b/packages/dsw-models/dsw/models/document_template/migrations.py
index 1005488c..8595f1a3 100644
--- a/packages/dsw-models/dsw/models/document_template/migrations.py
+++ b/packages/dsw-models/dsw/models/document_template/migrations.py
@@ -11,7 +11,8 @@
17.0 ``metamodelVersion`` became a ``"major.minor"`` string
18.3 ``language`` added (default ``"en"``)
19.0 no descriptor change (single ``id``, see below); the document context was restructured
-19.1 no descriptor change; questions have ``prefill`` and replies ``provenance`` in the context
+19.1 no descriptor change; questions have ``prefill`` and replies ``provenance`` in the
+ context, and the ``graphviz``, ``d2`` and ``chart`` steps and figure filters are new
======== =============================================================================
Whatever the version, the identity is upgraded to the single ``id`` of Wizard 5.0, as the
diff --git a/packages/dsw-tdk/CHANGELOG.md b/packages/dsw-tdk/CHANGELOG.md
index f567d281..c8dda6bc 100644
--- a/packages/dsw-tdk/CHANGELOG.md
+++ b/packages/dsw-tdk/CHANGELOG.md
@@ -11,6 +11,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Document template metamodel 19.1 and knowledge model metamodel 21; generated contexts have
`prefill` and `provenance`
+- `render` supports figures (`graphviz`, `d2`, `chart`, `svg`); `dot`, `d2` and `rsvg-convert` must
+ be installed for theirs, and text of the `svg` helper is wrapped with estimated widths
## [5.1.0]
diff --git a/packages/dsw-templating/CHANGELOG.md b/packages/dsw-templating/CHANGELOG.md
index d3bdc407..6754752b 100644
--- a/packages/dsw-templating/CHANGELOG.md
+++ b/packages/dsw-templating/CHANGELOG.md
@@ -10,6 +10,19 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
### Added
- `prefill` of questions and `provenance` of replies in the document context (metamodel 19.1)
+- Figures (metamodel 19.1, see `support/Figures.md`): the `graphviz`, `d2` and `chart` filters and
+ steps, `dot_escape` and `d2_escape`, and the `svg` global for custom figures; every SVG passes an
+ allow-list sanitizer and gets its own `id` prefix, and figures have `alt`, `title` and `desc`
+- `charts` extra (matplotlib), part of `all`
+- `FigureSettings` (renderer commands and timeouts, `FigureLimits`, fonts) in `RenderSettings`;
+ a document fails when it exceeds a limit
+
+### Changed
+
+- `tinycss2` is a dependency
+- External tools run through one helper: Pandoc and the figure renderers are stopped with
+ everything they started on a timeout, and the figure renderers also when they write more than
+ `max_output_bytes`
## [5.1.0]
diff --git a/packages/dsw-templating/README.md b/packages/dsw-templating/README.md
index 00202f90..c78f8e1c 100644
--- a/packages/dsw-templating/README.md
+++ b/packages/dsw-templating/README.md
@@ -20,6 +20,7 @@ pip install 'dsw-templating[all]' # every optional step dependency
| Extra | Needed for |
|---|---|
+| `charts` | `chart` filter and step (matplotlib) |
| `pdf` | `weasyprint` step (WeasyPrint, needs Pango installed) |
| `rdf` | `rdflib-convert` step and the `rdflib` global in Jinja templates |
| `excel` | `excel` step (XlsxWriter) |
@@ -27,7 +28,9 @@ pip install 'dsw-templating[all]' # every optional step dependency
| `http` | `requests` global in Jinja templates (Requests) |
A step whose extra is missing raises `MissingExtraError` ("install dsw-templating[pdf]") when it
-is used. The `pandoc` step needs the [pandoc](https://pandoc.org) executable.
+is used. The `pandoc` step needs the [pandoc](https://pandoc.org) executable, and the figures
+need [Graphviz](https://graphviz.org) (`dot`), [d2](https://d2lang.com) and `rsvg-convert`
+(librsvg) for `graphviz`, `d2` and the PNG of the `svg` helper.
## Usage
@@ -64,11 +67,14 @@ adds (service information and fallbacks for missing branding).
## Documentation for template developers
* [Document Context](./support/DocumentContext.md)
+* [Figures](./support/Figures.md)
* [Jinja Filters](./support/JinjaFilters.md)
* [Jinja Tests](./support/JinjaTests.md)
* [Translations](./support/Translations.md)
-* Steps: [archive](./support/steps/archive.md), [enrich-docx](./support/steps/enrich-docx.md),
- [excel](./support/steps/excel.md), [jinja](./support/steps/jinja.md), [json](./support/steps/json.md),
+* Steps: [archive](./support/steps/archive.md), [chart](./support/steps/chart.md),
+ [d2](./support/steps/d2.md), [enrich-docx](./support/steps/enrich-docx.md),
+ [excel](./support/steps/excel.md), [graphviz](./support/steps/graphviz.md),
+ [jinja](./support/steps/jinja.md), [json](./support/steps/json.md),
[pandoc](./support/steps/pandoc.md), [rdflib-convert](./support/steps/rdflib-convert.md),
[weasyprint](./support/steps/weasyprint.md)
diff --git a/packages/dsw-templating/dsw/templating/__init__.py b/packages/dsw-templating/dsw/templating/__init__.py
index 687c0fb3..7a9799b0 100644
--- a/packages/dsw-templating/dsw/templating/__init__.py
+++ b/packages/dsw-templating/dsw/templating/__init__.py
@@ -7,11 +7,14 @@
from .locales import RenderContext, TemplateLocale
from .plugins import create_manager, hookimpl, hookspec, register_plugin_steps
from .settings import (
+ FigureLimits,
+ FigureSettings,
PandocSettings,
RenderSettings,
RequestsSettings,
SecuritySettings,
TemplateSettings,
+ ToolSettings,
)
from .steps import FormatStepError, Step
from .steps.base import register_step
@@ -26,7 +29,7 @@
'Format', 'FormatStepError', 'Step', 'register_step',
'MissingExtraError', 'TemplateError', 'TemplateTriggeredError',
'RenderContext', 'TemplateLocale',
- 'PandocSettings', 'RenderSettings', 'RequestsSettings', 'SecuritySettings',
- 'TemplateSettings',
+ 'FigureLimits', 'FigureSettings', 'PandocSettings', 'RenderSettings',
+ 'RequestsSettings', 'SecuritySettings', 'TemplateSettings', 'ToolSettings',
'create_manager', 'hookimpl', 'hookspec', 'register_plugin_steps',
]
diff --git a/packages/dsw-templating/dsw/templating/conversions.py b/packages/dsw-templating/dsw/templating/conversions.py
index f609b1e3..a90ea45c 100644
--- a/packages/dsw-templating/dsw/templating/conversions.py
+++ b/packages/dsw-templating/dsw/templating/conversions.py
@@ -1,18 +1,13 @@
from __future__ import annotations
-import contextlib
import logging
-import os
import shlex
-import signal
-import subprocess
-import sys
-import tempfile
import typing
from . import consts
from .documents import FileFormat, FileFormats
from .exceptions import require
+from .process import ProcessError, run_process
if typing.TYPE_CHECKING:
@@ -22,67 +17,15 @@
LOG = logging.getLogger(__name__)
-#: how much of the end of stderr goes into the error message
-STDERR_LIMIT = 64 * 1024
-
-
def run_conversion(*, args: list, workdir: str, input_data: bytes, name: str,
source_format: FileFormat, target_format: FileFormat, timeout=None) -> bytes:
command = ' '.join(args)
LOG.info('Calling "%s" to convert from %s to %s',
command, source_format, target_format)
- # output goes to temporary files (deleted on close), not pipes, so nothing
- # blocks on a full pipe and stderr is read only up to STDERR_LIMIT
- with tempfile.TemporaryFile() as stdout, tempfile.TemporaryFile() as stderr:
- try:
- # own process group (POSIX), so a timeout stops also the filters it started
- proc = subprocess.Popen(args, cwd=workdir, stdin=subprocess.PIPE,
- stdout=stdout, stderr=stderr,
- start_new_session=True)
- except FileNotFoundError as e:
- raise FormatConversionError(
- name, source_format, target_format,
- f'Executable "{args[0]}" not found, is it installed?',
- ) from e
- try:
- proc.communicate(input=input_data, timeout=timeout)
- except subprocess.TimeoutExpired as e:
- _kill(proc)
- raise FormatConversionError(
- name, source_format, target_format,
- f'Exceeded the time limit of {timeout} seconds and was stopped',
- ) from e
- except BaseException:
- _kill(proc)
- raise
- if proc.returncode != consts.EXIT_SUCCESS:
- raise FormatConversionError(
- name, source_format, target_format,
- f'Failed to execute (exit code: {proc.returncode}): '
- f'{_read_tail(stderr, STDERR_LIMIT).decode(consts.DEFAULT_ENCODING, "replace")}',
- )
- stdout.seek(0)
- return stdout.read()
-
-
-def _kill(proc: subprocess.Popen):
- """Kill the process with everything it started, and reap it."""
- if sys.platform == 'win32':
- proc.kill()
- else:
- # the group is still there, the leader has not been reaped yet
- with contextlib.suppress(ProcessLookupError):
- os.killpg(proc.pid, signal.SIGKILL)
- if proc.stdin:
- with contextlib.suppress(OSError):
- proc.stdin.close()
- proc.wait()
-
-
-def _read_tail(file: typing.BinaryIO, limit: int) -> bytes:
- size = file.seek(0, os.SEEK_END)
- file.seek(max(0, size - limit))
- return file.read()
+ try:
+ return run_process(args, workdir=workdir, input_data=input_data, timeout=timeout)
+ except ProcessError as e:
+ raise FormatConversionError(name, source_format, target_format, e.message) from e
class FormatConversionError(Exception):
diff --git a/packages/dsw-templating/dsw/templating/documents.py b/packages/dsw-templating/dsw/templating/documents.py
index 6a298b7a..c17c46b1 100644
--- a/packages/dsw-templating/dsw/templating/documents.py
+++ b/packages/dsw-templating/dsw/templating/documents.py
@@ -69,6 +69,8 @@ class FileFormats:
'application/vnd.ms-excel.sheet.macroEnabled.12',
'xlsm',
)
+ SVG = FileFormat('svg', 'image/svg+xml', 'svg')
+ PNG = FileFormat('png', 'image/png', 'png')
@staticmethod
def get(name: str):
@@ -104,6 +106,8 @@ def get(name: str):
'lzma': FileFormats.TAR_LZMA,
'xlsx': FileFormats.XLSX,
'xlsm': FileFormats.XLSM,
+ 'svg': FileFormats.SVG,
+ 'png': FileFormats.PNG,
}
return known_formats.get(name)
diff --git a/packages/dsw-templating/dsw/templating/figures/__init__.py b/packages/dsw-templating/dsw/templating/figures/__init__.py
new file mode 100644
index 00000000..2a75b39e
--- /dev/null
+++ b/packages/dsw-templating/dsw/templating/figures/__init__.py
@@ -0,0 +1,8 @@
+"""Figures in documents: Graphviz, d2, charts and the `svg` helper."""
+from .base import Figure, FigureError
+from .d2 import d2_escape
+from .graphviz import dot_escape
+from .service import Figures
+
+
+__all__ = ['Figure', 'FigureError', 'Figures', 'd2_escape', 'dot_escape']
diff --git a/packages/dsw-templating/dsw/templating/figures/base.py b/packages/dsw-templating/dsw/templating/figures/base.py
new file mode 100644
index 00000000..6a251477
--- /dev/null
+++ b/packages/dsw-templating/dsw/templating/figures/base.py
@@ -0,0 +1,120 @@
+from __future__ import annotations
+
+import base64
+import contextlib
+import html
+import time
+import typing
+
+import jinja2.exceptions
+import markupsafe
+
+from .. import consts
+
+
+if typing.TYPE_CHECKING:
+ from ..settings import FigureLimits
+
+
+SVG = 'svg'
+PNG = 'png'
+PDF = 'pdf'
+
+CONTENT_TYPES = {
+ SVG: 'image/svg+xml',
+ PNG: 'image/png',
+ PDF: 'application/pdf',
+}
+
+
+def plain_text(value: typing.Any) -> str:
+ """The text of a value; Markup is HTML (a macro's output, say), so its entities are decoded."""
+ if isinstance(value, markupsafe.Markup):
+ return value.unescape()
+ return str(value)
+
+
+class FigureError(jinja2.exceptions.TemplateRuntimeError):
+ """A figure that cannot be rendered; fails the document."""
+
+ def __init__(self, renderer: str, message: str):
+ self.renderer = renderer
+ # `message` is Jinja's own property, the whole text
+ super().__init__(f'{renderer}: {message}')
+
+
+class Figure:
+ """A rendered figure; printed as inline SVG, or as an ``
`` for PNG."""
+
+ def __init__(self, data: bytes, fmt: str, *, alt: str | None = None):
+ self.data = data
+ self.format = fmt
+ self.alt = alt
+
+ @property
+ def content_type(self) -> str:
+ return CONTENT_TYPES[self.format]
+
+ @property
+ def svg(self) -> str:
+ if self.format != SVG:
+ raise FigureError('figure', f'A {self.format} figure has no SVG markup')
+ return self.data.decode(consts.DEFAULT_ENCODING)
+
+ @property
+ def data_url(self) -> str:
+ return f'data:{self.content_type};base64,{base64.b64encode(self.data).decode("ascii")}'
+
+ def __html__(self) -> str:
+ if self.format == SVG:
+ return self.svg
+ if self.format == PNG:
+ return f'
'
+ raise FigureError('figure', f'A {self.format} figure cannot be printed into a document')
+
+ def __str__(self) -> str:
+ return markupsafe.Markup(self.__html__()) # noqa: S704 (sanitized SVG or an escaped
)
+
+
+def check_format(renderer: str, fmt: str, allowed: typing.Iterable[str]) -> str:
+ allowed = tuple(allowed)
+ if fmt not in allowed:
+ raise FigureError(renderer, f'Unknown format "{fmt}", use one of: {", ".join(allowed)}')
+ return fmt
+
+
+class FigureBudget:
+ """Number of figures and total render time of one document."""
+
+ def __init__(self, limits: FigureLimits):
+ self.limits = limits
+ self.count = 0
+ self.seconds = 0.0
+
+ def reset(self):
+ self.count = 0
+ self.seconds = 0.0
+
+ def remaining_seconds(self) -> float:
+ return max(0.0, self.limits.max_render_seconds - self.seconds)
+
+ @contextlib.contextmanager
+ def track(self, renderer: str):
+ if self.count >= self.limits.max_figures:
+ raise FigureError(renderer, f'More than {self.limits.max_figures} figures '
+ f'in one document (limit max_figures)')
+ if self.remaining_seconds() <= 0:
+ raise _time_exceeded(renderer, self.limits.max_render_seconds)
+ self.count += 1
+ start = time.monotonic()
+ try:
+ yield
+ finally:
+ self.seconds += time.monotonic() - start
+ if self.seconds > self.limits.max_render_seconds:
+ raise _time_exceeded(renderer, self.limits.max_render_seconds)
+
+
+def _time_exceeded(renderer: str, limit: float) -> FigureError:
+ return FigureError(renderer, f'Figures of one document took more than {limit} seconds '
+ f'to render (limit max_render_seconds)')
diff --git a/packages/dsw-templating/dsw/templating/figures/chart.py b/packages/dsw-templating/dsw/templating/figures/chart.py
new file mode 100644
index 00000000..85ab8c3a
--- /dev/null
+++ b/packages/dsw-templating/dsw/templating/figures/chart.py
@@ -0,0 +1,657 @@
+"""Charts from a small declarative JSON spec, rendered with matplotlib.
+
+An invalid spec fails; missing data does not. A ``null`` value is a gap (never 0), a timeline
+task without dates is left out and listed under the chart, and no data at all gives an empty
+figure showing ``emptyText``.
+"""
+from __future__ import annotations
+
+import dataclasses
+import datetime
+import functools
+import io
+import json
+import math
+import numbers
+import pathlib
+import re
+import typing
+
+import jinja2
+
+from ..exceptions import require
+from .base import FigureError, plain_text
+
+
+if typing.TYPE_CHECKING:
+ from ..settings import FigureLimits
+
+
+FORMATS = ('svg', 'png', 'pdf')
+
+SERIES_TYPES = ('bar', 'barh', 'stacked-bar', 'line', 'scatter')
+PIE_TYPES = ('pie', 'donut')
+TYPES = (*SERIES_TYPES, *PIE_TYPES, 'timeline')
+
+COMMON_KEYS = frozenset({'type', 'title', 'xLabel', 'yLabel', 'legend', 'size', 'colors',
+ 'valueLabels', 'referenceLines', 'emptyText'})
+TYPE_KEYS = {
+ **dict.fromkeys(SERIES_TYPES, frozenset({'labels', 'series'})),
+ 'pie': frozenset({'labels', 'series'}),
+ 'donut': frozenset({'labels', 'series', 'centerText'}),
+ 'timeline': frozenset({'tasks', 'milestones'}),
+}
+REQUIRED_KEYS = {
+ **dict.fromkeys((*SERIES_TYPES, *PIE_TYPES), ('labels', 'series')),
+ 'timeline': ('tasks',),
+}
+PERCENT_TYPES = ('pie', 'donut', 'stacked-bar')
+SIZE_UNITS = {'px': 1 / 100, 'in': 1, 'cm': 1 / 2.54, 'mm': 1 / 25.4, 'pt': 1 / 72}
+DPI = 100
+#: longer labels, series names and task labels end with an ellipsis
+MAX_LABEL_LENGTH = 40
+DEFAULT_SIZE = (6.4, 4.0)
+DEFAULT_EMPTY_TEXT = 'No data'
+FONT_FAMILY = ['Noto Sans', 'DejaVu Sans']
+
+_DATE = re.compile(r'^\d{4}-\d{2}-\d{2}$')
+
+
+def _fail(message: str) -> typing.NoReturn:
+ raise FigureError('chart', message)
+
+
+@dataclasses.dataclass
+class Series:
+ name: str
+ values: list[float | None]
+
+
+@dataclasses.dataclass
+class Task:
+ label: str
+ start: datetime.date | None
+ end: datetime.date | None
+ group: str | None
+
+
+@dataclasses.dataclass
+class ReferenceLine:
+ axis: str
+ value: float | datetime.date
+ label: str | None
+
+
+@dataclasses.dataclass
+class ChartSpec:
+ type: str
+ title: str | None = None
+ x_label: str | None = None
+ y_label: str | None = None
+ legend: bool | None = None
+ size: tuple[float, float] = DEFAULT_SIZE
+ colors: list[str] | None = None
+ value_labels: bool | str = False
+ reference_lines: list[ReferenceLine] = dataclasses.field(default_factory=list)
+ empty_text: str = DEFAULT_EMPTY_TEXT
+ labels: list = dataclasses.field(default_factory=list)
+ series: list[Series] = dataclasses.field(default_factory=list)
+ center_text: str | None = None
+ tasks: list[Task] = dataclasses.field(default_factory=list)
+ milestones: list[tuple[str, datetime.date]] = dataclasses.field(default_factory=list)
+
+ @property
+ def date_labels(self) -> bool:
+ return bool(self.labels) and all(isinstance(x, datetime.date) for x in self.labels)
+
+ @property
+ def numeric_labels(self) -> bool:
+ return bool(self.labels) and all(isinstance(x, float) for x in self.labels)
+
+
+# Parsing and validation
+
+def parse_spec(spec: typing.Any, limits: FigureLimits) -> ChartSpec:
+ spec = _load(spec, limits)
+ chart_type = spec.get('type')
+ if chart_type not in TYPES:
+ _fail(f'Unknown type "{chart_type}", use one of: {", ".join(TYPES)}')
+ for key in spec:
+ if key not in COMMON_KEYS and key not in TYPE_KEYS[chart_type]:
+ _fail(f'Unknown key "{key}" for type "{chart_type}"')
+ for key in REQUIRED_KEYS[chart_type]:
+ if key not in spec:
+ _fail(f'Missing key "{key}"')
+ result = ChartSpec(type=chart_type)
+ result.title = _optional_str(spec, 'title')
+ result.x_label = _optional_str(spec, 'xLabel')
+ result.y_label = _optional_str(spec, 'yLabel')
+ result.legend = _optional_bool(spec, 'legend')
+ result.size = _size(spec.get('size'), limits)
+ result.colors = _colors(spec.get('colors'))
+ result.value_labels = _value_labels(spec.get('valueLabels', False), chart_type)
+ result.empty_text = _optional_str(spec, 'emptyText') or DEFAULT_EMPTY_TEXT
+ if chart_type == 'timeline':
+ result.tasks = _tasks(spec['tasks'])
+ result.milestones = _milestones(spec.get('milestones', []))
+ points = len(result.tasks) + len(result.milestones)
+ else:
+ points = _parse_series_data(spec, result, limits)
+ if points > limits.max_chart_points:
+ _fail(f'More than {limits.max_chart_points} points (limit max_chart_points)')
+ result.reference_lines = _reference_lines(spec.get('referenceLines', []), result)
+ return result
+
+
+def _load(spec: typing.Any, limits: FigureLimits) -> dict:
+ spec = _plain(spec)
+ if isinstance(spec, str):
+ if len(spec.encode()) > limits.max_chart_spec_bytes:
+ _spec_too_large(limits)
+ try:
+ spec = json.loads(spec, parse_constant=_reject_constant)
+ except ValueError as e:
+ _fail(f'Invalid JSON: {e}')
+ if not isinstance(spec, dict):
+ _fail('The spec must be an object (a dict)')
+ if len(json.dumps(spec, default=str).encode()) > limits.max_chart_spec_bytes:
+ _spec_too_large(limits)
+ return spec
+
+
+def _plain(value: typing.Any) -> typing.Any:
+ """The spec with every Markup (HTML, such as a macro's output) as the text it shows."""
+ if isinstance(value, str):
+ return plain_text(value)
+ if isinstance(value, dict):
+ return {_plain(key): _plain(item) for key, item in value.items()}
+ if isinstance(value, list | tuple):
+ return [_plain(item) for item in value]
+ return value
+
+
+def _short(text: str) -> str:
+ """A label that leaves room for the plot; the full text belongs in the document."""
+ return text if len(text) <= MAX_LABEL_LENGTH else text[:MAX_LABEL_LENGTH - 1].rstrip() + '…'
+
+
+def _parse_series_data(spec: dict, result: ChartSpec, limits: FigureLimits) -> int:
+ result.labels = _labels(spec['labels'], result.type)
+ result.series = _series(spec['series'], len(result.labels), result.type)
+ result.center_text = _optional_str(spec, 'centerText')
+ if len(result.labels) > limits.max_chart_labels:
+ _fail(f'More than {limits.max_chart_labels} labels (limit max_chart_labels)')
+ if len(result.series) > limits.max_chart_series:
+ _fail(f'More than {limits.max_chart_series} series (limit max_chart_series)')
+ return sum(len(s.values) for s in result.series)
+
+
+def _spec_too_large(limits: FigureLimits) -> typing.NoReturn:
+ _fail(f'The spec has more than {limits.max_chart_spec_bytes} bytes '
+ f'(limit max_chart_spec_bytes)')
+
+
+def _reject_constant(name: str):
+ _fail(f'{name} is not allowed')
+
+
+def _is_missing(value) -> bool:
+ return value is None or isinstance(value, jinja2.Undefined)
+
+
+def _optional_str(spec: dict, key: str) -> str | None:
+ value = spec.get(key)
+ if _is_missing(value):
+ return None
+ if not isinstance(value, str):
+ _fail(f'"{key}" must be a string')
+ return value
+
+
+def _optional_bool(spec: dict, key: str) -> bool | None:
+ value = spec.get(key)
+ if value is None:
+ return None
+ if not isinstance(value, bool):
+ _fail(f'"{key}" must be true or false')
+ return value
+
+
+def _number(value, where: str) -> float | None:
+ if _is_missing(value):
+ return None
+ if isinstance(value, bool) or not isinstance(value, numbers.Real):
+ _fail(f'{where} must be a number or null, not {type(value).__name__}')
+ result = float(value)
+ if not math.isfinite(result):
+ _fail(f'{where} is {value}, NaN and Infinity are not allowed')
+ return result
+
+
+def _date(value, where: str) -> datetime.date:
+ if isinstance(value, datetime.datetime):
+ return value.date()
+ if isinstance(value, datetime.date):
+ return value
+ if not isinstance(value, str) or not _DATE.match(value):
+ _fail(f'{where} must be a date as YYYY-MM-DD, not "{value}"')
+ try:
+ return datetime.date.fromisoformat(value)
+ except ValueError:
+ _fail(f'{where} is not a valid date: "{value}"')
+
+
+def _list(value, key: str) -> list:
+ if not isinstance(value, list | tuple):
+ _fail(f'"{key}" must be a list')
+ return list(value)
+
+
+def _size(value, limits: FigureLimits) -> tuple[float, float]:
+ if value is None:
+ return DEFAULT_SIZE
+ if not isinstance(value, dict):
+ _fail('"size" must be an object with "width" and "height"')
+ for key in value:
+ if key not in ('width', 'height', 'unit'):
+ _fail(f'Unknown key "{key}" in "size"')
+ unit = value.get('unit', 'px')
+ if unit not in SIZE_UNITS:
+ _fail(f'Unknown size unit "{unit}", use one of: {", ".join(SIZE_UNITS)}')
+ width = _number(value.get('width'), '"size.width"')
+ height = _number(value.get('height'), '"size.height"')
+ if width is None or height is None or width <= 0 or height <= 0:
+ _fail('"size" needs a positive "width" and "height"')
+ inches = (width * SIZE_UNITS[unit], height * SIZE_UNITS[unit])
+ if max(inches) * DPI > limits.max_size_px:
+ _fail(f'The chart is larger than {limits.max_size_px} px (limit max_size_px)')
+ return inches
+
+
+def _colors(value) -> list[str] | None:
+ if value is None:
+ return None
+ colors = _list(value, 'colors')
+ for index, color in enumerate(colors):
+ if not isinstance(color, str):
+ _fail(f'Color {index} must be a string')
+ return colors
+
+
+def _value_labels(value, chart_type: str) -> bool | str:
+ if isinstance(value, bool):
+ return value
+ if value == 'percent':
+ if chart_type not in PERCENT_TYPES:
+ _fail(f'"valueLabels": "percent" is only for {", ".join(PERCENT_TYPES)}')
+ return value
+ _fail('"valueLabels" must be true, false or "percent"')
+
+
+def _labels(value, chart_type: str) -> list:
+ labels = _list(value, 'labels')
+ result = []
+ for index, label in enumerate(labels):
+ if isinstance(label, bool) or not isinstance(label, str | numbers.Real):
+ _fail(f'Label {index} must be a string or a number')
+ result.append(label)
+ if chart_type in ('line', 'scatter'):
+ if result and all(isinstance(x, numbers.Real) for x in result):
+ return [_number(x, f'Label {i}') for i, x in enumerate(result)]
+ if any(isinstance(x, str) and _DATE.match(x) for x in result):
+ return [_date(x, f'Label {i}') for i, x in enumerate(result)]
+ return [_short(str(x)) for x in result]
+
+
+def _series(value, size: int, chart_type: str) -> list[Series]:
+ result = [_one_series(index, item, size, chart_type)
+ for index, item in enumerate(_list(value, 'series'))]
+ if chart_type in PIE_TYPES and len(result) != 1:
+ _fail(f'A {chart_type} chart takes exactly one series')
+ return result
+
+
+def _one_series(index: int, item, size: int, chart_type: str) -> Series:
+ if not isinstance(item, dict):
+ _fail(f'Series {index} must be an object with "name" and "values"')
+ for key in item:
+ if key not in ('name', 'values'):
+ _fail(f'Unknown key "{key}" in series {index}')
+ name = item.get('name')
+ name = f'Series {index + 1}' if _is_missing(name) else _short(str(name))
+ if 'values' not in item:
+ _fail(f'Series "{name}" has no "values"')
+ values = _list(item['values'], f'series "{name}" values')
+ if len(values) != size:
+ _fail(f'Series "{name}" has {len(values)} values for {size} labels')
+ result = [_number(v, f'Series "{name}" value {i}') for i, v in enumerate(values)]
+ if chart_type in PIE_TYPES:
+ for i, number in enumerate(result):
+ if number is not None and number < 0:
+ _fail(f'Series "{name}" value {i} is negative, not allowed in {chart_type}')
+ return Series(name, result)
+
+
+def _tasks(value) -> list[Task]:
+ result = []
+ for index, item in enumerate(_list(value, 'tasks')):
+ if not isinstance(item, dict):
+ _fail(f'Task {index} must be an object')
+ label = item.get('label')
+ if not isinstance(label, str):
+ _fail(f'Task {index} needs a "label" string')
+ for key in item:
+ if key not in ('label', 'start', 'end', 'group'):
+ _fail(f'Unknown key "{key}" in task "{label}"')
+ start = None if _is_missing(item.get('start')) \
+ else _date(item['start'], f'Task "{label}" start')
+ end = None if _is_missing(item.get('end')) \
+ else _date(item['end'], f'Task "{label}" end')
+ if start is not None and end is not None and end < start:
+ _fail(f'Task "{label}" ends before it starts')
+ group = item.get('group')
+ result.append(Task(_short(label), start, end,
+ None if _is_missing(group) else _short(str(group))))
+ return result
+
+
+def _milestones(value) -> list[tuple[str, datetime.date]]:
+ result = []
+ for index, item in enumerate(_list(value, 'milestones')):
+ if not isinstance(item, dict) or not isinstance(item.get('label'), str):
+ _fail(f'Milestone {index} must be an object with "label" and "date"')
+ for key in item:
+ if key not in ('label', 'date'):
+ _fail(f'Unknown key "{key}" in milestone "{item["label"]}"')
+ result.append((_short(item['label']),
+ _date(item.get('date'), f'Milestone "{item["label"]}" date')))
+ return result
+
+
+def _reference_lines(value, spec: ChartSpec) -> list[ReferenceLine]:
+ result = []
+ for index, item in enumerate(_list(value, 'referenceLines')):
+ if not isinstance(item, dict):
+ _fail(f'Reference line {index} must be an object')
+ for key in item:
+ if key not in ('axis', 'value', 'label'):
+ _fail(f'Unknown key "{key}" in reference line {index}')
+ axis = item.get('axis', 'y')
+ if axis not in ('x', 'y'):
+ _fail(f'Reference line {index}: "axis" must be "x" or "y"')
+ where = f'Reference line {index} value'
+ if spec.type == 'timeline' or (axis == 'x' and spec.date_labels):
+ line_value: float | datetime.date = _date(item.get('value'), where)
+ else:
+ number = _number(item.get('value'), where)
+ if number is None:
+ _fail(f'{where} is missing')
+ line_value = number
+ label = item.get('label')
+ result.append(ReferenceLine(axis, line_value, None if _is_missing(label) else str(label)))
+ return result
+
+
+# Rendering
+
+def render(spec: typing.Any, fmt: str, *, limits: FigureLimits,
+ font_dir: pathlib.Path | None) -> bytes:
+ matplotlib = require('matplotlib', 'charts')
+ chart = parse_spec(spec, limits)
+ from matplotlib.figure import Figure # noqa: PLC0415 (optional dependency)
+ families = _register_fonts(str(font_dir)) if font_dir else []
+ rc = {
+ 'svg.fonttype': 'path',
+ 'svg.hashsalt': 'dsw-chart',
+ 'axes.spines.top': False,
+ 'axes.spines.right': False,
+ 'font.family': [*families, 'DejaVu Sans'],
+ }
+ if chart.colors:
+ try:
+ rc['axes.prop_cycle'] = matplotlib.cycler(color=chart.colors)
+ except ValueError as e:
+ _fail(f'Invalid "colors": {e}')
+ with matplotlib.rc_context(rc):
+ figure = Figure(figsize=chart.size, dpi=DPI, layout='constrained')
+ ax = figure.add_subplot()
+ note = None
+ if _is_empty(chart):
+ _draw_empty(ax, chart)
+ else:
+ note = _DRAWERS[chart.type](ax, chart)
+ _draw_reference_lines(ax, chart)
+ if chart.x_label:
+ ax.set_xlabel(chart.x_label)
+ if chart.y_label:
+ ax.set_ylabel(chart.y_label)
+ if chart.title:
+ # room for the labels of vertical reference lines, printed above the plot
+ labelled = any(line.label and line.axis != 'y' for line in chart.reference_lines)
+ ax.set_title(chart.title, pad=18 if labelled else 6)
+ if note:
+ figure.supxlabel(note, fontsize='small', color='#555555')
+ output = io.BytesIO()
+ figure.savefig(output, format=fmt, dpi=DPI, metadata=_METADATA[fmt])
+ return output.getvalue()
+
+
+_METADATA: dict[str, dict] = {
+ 'svg': {'Date': None, 'Creator': None},
+ 'png': {'Software': None},
+ 'pdf': {'CreationDate': None, 'Creator': None, 'Producer': None},
+}
+
+
+@functools.cache
+def _register_fonts(font_dir: str) -> list[str]:
+ from matplotlib import font_manager # noqa: PLC0415 (optional dependency)
+ families = []
+ for path in sorted(pathlib.Path(font_dir).glob('*.[ot]tf')):
+ if 'emoji' in path.name.lower():
+ continue # colour bitmap fonts cannot be drawn
+ font_manager.fontManager.addfont(str(path))
+ name = font_manager.FontProperties(fname=str(path)).get_name()
+ if name not in families:
+ families.append(name)
+ # sans-serif first, as for the rest of the document
+ return sorted(families, key=lambda name: (name not in FONT_FAMILY, name))
+
+
+def _is_empty(chart: ChartSpec) -> bool:
+ if chart.type == 'timeline':
+ return not any(t.start and t.end for t in chart.tasks) and not chart.milestones
+ if not chart.labels or all(v is None for s in chart.series for v in s.values):
+ return True
+ if chart.type in PIE_TYPES:
+ return sum(v or 0 for v in chart.series[0].values) == 0
+ return False
+
+
+def _draw_empty(ax, chart: ChartSpec):
+ ax.set_axis_off()
+ ax.text(0.5, 0.5, chart.empty_text, ha='center', va='center',
+ transform=ax.transAxes, color='#777777', fontsize='large')
+
+
+def _format(value: float) -> str:
+ return str(int(value)) if value.is_integer() else f'{value:g}'
+
+
+def _nan(values: list[float | None]) -> list[float]:
+ return [math.nan if v is None else v for v in values]
+
+
+def _color(chart: ChartSpec, index: int):
+ return chart.colors[index % len(chart.colors)] if chart.colors else f'C{index % 10}'
+
+
+def _show_legend(chart: ChartSpec, default: bool) -> bool:
+ return default if chart.legend is None else chart.legend
+
+
+def _draw_bars(ax, chart: ChartSpec):
+ horizontal = chart.type == 'barh'
+ stacked = chart.type == 'stacked-bar'
+ positions = list(range(len(chart.labels)))
+ width = 0.8 if stacked else 0.8 / len(chart.series)
+ bottoms = [0.0] * len(positions)
+ totals = [sum(s.values[i] or 0 for s in chart.series) for i in positions]
+ for index, series in enumerate(chart.series):
+ values = _nan(series.values)
+ if stacked:
+ where = positions
+ offset = {'bottom': list(bottoms)}
+ else:
+ where = [p - 0.4 + width * (index + 0.5) for p in positions]
+ offset = {}
+ draw = ax.barh if horizontal else ax.bar
+ if horizontal:
+ offset = {'left': offset['bottom']} if offset else {}
+ bars = draw(where, values, width, label=series.name, color=_color(chart, index), **offset)
+ if stacked:
+ bottoms = [b + (v or 0) for b, v in zip(bottoms, series.values, strict=True)]
+ if chart.value_labels:
+ ax.bar_label(bars, labels=_bar_texts(chart, series, totals),
+ label_type='center' if stacked else 'edge')
+ if horizontal:
+ ax.set_yticks(positions, chart.labels)
+ ax.invert_yaxis()
+ else:
+ ax.set_xticks(positions, chart.labels)
+ if _show_legend(chart, len(chart.series) > 1):
+ ax.legend()
+
+
+def _bar_texts(chart: ChartSpec, series: Series, totals: list[float]) -> list[str]:
+ texts = []
+ for value, total in zip(series.values, totals, strict=True):
+ if value is None or (value == 0 and chart.type == 'stacked-bar'):
+ texts.append('') # a gap has no value to print, an empty segment no room
+ elif chart.value_labels == 'percent':
+ texts.append(f'{value / total * 100:.0f}%' if total else '')
+ else:
+ texts.append(_format(value))
+ return texts
+
+
+def _x_values(chart: ChartSpec) -> list:
+ if chart.date_labels or chart.numeric_labels:
+ return chart.labels
+ return list(range(len(chart.labels)))
+
+
+def _draw_points(ax, chart: ChartSpec):
+ xs = _x_values(chart)
+ for index, series in enumerate(chart.series):
+ color = _color(chart, index)
+ if chart.type == 'line':
+ ax.plot(xs, _nan(series.values), marker='o', label=series.name, color=color)
+ else:
+ points = [(x, v) for x, v in zip(xs, series.values, strict=True) if v is not None]
+ ax.scatter([p[0] for p in points], [p[1] for p in points], label=series.name,
+ color=color)
+ if chart.value_labels:
+ for x, value in zip(xs, series.values, strict=True):
+ if value is not None:
+ ax.annotate(_format(value), (x, value), textcoords='offset points',
+ xytext=(0, 5), ha='center', fontsize='small')
+ if not (chart.date_labels or chart.numeric_labels):
+ ax.set_xticks(xs, chart.labels)
+ if chart.date_labels:
+ _date_axis(ax)
+ if _show_legend(chart, len(chart.series) > 1):
+ ax.legend()
+
+
+def _draw_pie(ax, chart: ChartSpec):
+ pairs = [(label, value) for label, value in zip(chart.labels, chart.series[0].values,
+ strict=True) if value]
+ labels = [p[0] for p in pairs]
+ values = [p[1] for p in pairs]
+ total = sum(values)
+ legend = _show_legend(chart, False)
+ autopct = None
+ if chart.value_labels == 'percent':
+ autopct = '%1.0f%%'
+ elif chart.value_labels:
+ def autopct(pct):
+ return _format(round(pct * total / 100, 6))
+ colors = [_color(chart, i) for i in range(len(values))]
+ result = ax.pie(values, labels=None if legend else labels, colors=colors, autopct=autopct,
+ startangle=90, counterclock=False,
+ wedgeprops={'width': 0.4} if chart.type == 'donut' else None,
+ pctdistance=0.8 if chart.type == 'donut' else 0.6)
+ if chart.type == 'donut' and chart.center_text:
+ ax.text(0, 0, chart.center_text, ha='center', va='center', fontsize='x-large')
+ ax.set_aspect('equal')
+ if legend:
+ ax.legend(result[0], labels, loc='center left', bbox_to_anchor=(1, 0.5))
+
+
+def _draw_timeline(ax, chart: ChartSpec) -> str | None:
+ dates = require('matplotlib.dates', 'charts')
+ shown = [t for t in chart.tasks if t.start and t.end]
+ left_out = [t.label for t in chart.tasks if not (t.start and t.end)]
+ groups: dict[str | None, int] = {}
+ for task in shown:
+ groups.setdefault(task.group, len(groups))
+ labelled = set()
+ for row, task in enumerate(shown):
+ start = dates.date2num(task.start)
+ days = (typing.cast('datetime.date', task.end)
+ - typing.cast('datetime.date', task.start)).days
+ group = groups[task.group]
+ label = task.group if task.group is not None and task.group not in labelled else None
+ labelled.add(task.group)
+ # the end date is included
+ ax.barh(row, days + 1, left=start, height=0.6, color=_color(chart, group), label=label)
+ for label, date in chart.milestones:
+ x = dates.date2num(date)
+ ax.axvline(x, color='#444444', linestyle=':', linewidth=1)
+ ax.plot([x], [-0.7], marker='D', color='#444444', clip_on=False)
+ ax.annotate(label, (x, -0.7), textcoords='offset points', xytext=(6, 0), va='center',
+ fontsize='small', annotation_clip=False)
+ ax.set_yticks(range(len(shown)), [t.label for t in shown])
+ ax.set_ylim(len(shown) - 0.5, -1)
+ _date_axis(ax)
+ if _show_legend(chart, any(g is not None for g in groups)):
+ ax.legend()
+ if left_out:
+ return f'Without start or end: {", ".join(left_out)}'
+ return None
+
+
+def _date_axis(ax):
+ dates = require('matplotlib.dates', 'charts')
+ locator = dates.AutoDateLocator()
+ ax.xaxis.set_major_locator(locator)
+ ax.xaxis.set_major_formatter(dates.ConciseDateFormatter(locator))
+
+
+def _draw_reference_lines(ax, chart: ChartSpec):
+ dates = require('matplotlib.dates', 'charts')
+ for line in chart.reference_lines:
+ value = dates.date2num(line.value) if isinstance(line.value, datetime.date) else line.value
+ if line.axis == 'y':
+ ax.axhline(value, color='#555555', linestyle='--', linewidth=1)
+ if line.label:
+ ax.text(1, value, line.label, transform=ax.get_yaxis_transform(), ha='right',
+ va='bottom', fontsize='small', color='#555555')
+ else:
+ ax.axvline(value, color='#555555', linestyle='--', linewidth=1)
+ if line.label:
+ ax.text(value, 1, line.label, transform=ax.get_xaxis_transform(), ha='center',
+ va='bottom', fontsize='small', color='#555555')
+
+
+_DRAWERS: dict[str, typing.Callable] = {
+ 'bar': _draw_bars,
+ 'barh': _draw_bars,
+ 'stacked-bar': _draw_bars,
+ 'line': _draw_points,
+ 'scatter': _draw_points,
+ 'pie': _draw_pie,
+ 'donut': _draw_pie,
+ 'timeline': _draw_timeline,
+}
diff --git a/packages/dsw-templating/dsw/templating/figures/d2.py b/packages/dsw-templating/dsw/templating/figures/d2.py
new file mode 100644
index 00000000..4ee4175c
--- /dev/null
+++ b/packages/dsw-templating/dsw/templating/figures/d2.py
@@ -0,0 +1,56 @@
+"""d2 diagrams, rendered by the ``d2`` binary."""
+from __future__ import annotations
+
+import re
+
+import markupsafe
+
+from .base import FigureError, plain_text
+
+
+FORMATS = ('svg', 'png')
+
+_STRING = re.compile(r'"(?:\\.|[^"\\])*"|\'[^\'\n]*\'')
+#: quoted keys still count, `"icon": ...` is an icon
+_KEYWORDS = frozenset({'icon', 'shape', 'image'})
+_REJECTED = (
+ (re.compile(r'(^|[\s{;.])icon\s*:'), 'Icons are not allowed'),
+ (re.compile(r'(^|[\s{;.])shape\s*:\s*image\b'), 'Images ("shape: image") are not allowed'),
+ (re.compile(r'(:|\.\.\.)\s*@'), 'Imports are not allowed'),
+)
+_OPTION = re.compile(r'^[\w][\w -]*$')
+
+
+def d2_escape(value) -> markupsafe.Markup:
+ """Make a text safe inside a double-quoted d2 key or label."""
+ text = plain_text(value)
+ text = text.replace('\\', '\\\\').replace('"', '\\"').replace('$', '\\$')
+ text = text.replace('\r\n', '\\n').replace('\n', '\\n').replace('\r', '\\n')
+ return markupsafe.Markup(text) # noqa: S704 (escaped for the figure source above)
+
+
+def check_source(source: str):
+ """Refuse imports, icons and images, which read files or fetch URLs, before d2 runs.
+
+ d2 also runs with local files disallowed and without bundling images, so nothing is read
+ or fetched even when this check misses something.
+ """
+ def keep_keyword(match: re.Match) -> str:
+ content = match.group()[1:-1]
+ return content if content in _KEYWORDS else '""'
+
+ code = _STRING.sub(keep_keyword, source)
+ for pattern, message in _REJECTED:
+ if pattern.search(code):
+ raise FigureError('d2', message)
+
+
+def args(layout: str | None, theme: str | int | None, fmt: str) -> list[str]:
+ result = ['--bundle=false', '--allow-local-files=false', '--stdout-format', fmt]
+ for name, value in (('layout', layout), ('theme', theme)):
+ if value is None:
+ continue
+ if not _OPTION.match(str(value)):
+ raise FigureError('d2', f'Invalid {name} "{value}"')
+ result.append(f'--{name}={value}')
+ return [*result, '-', '-']
diff --git a/packages/dsw-templating/dsw/templating/figures/graphviz.py b/packages/dsw-templating/dsw/templating/figures/graphviz.py
new file mode 100644
index 00000000..874b8953
--- /dev/null
+++ b/packages/dsw-templating/dsw/templating/figures/graphviz.py
@@ -0,0 +1,111 @@
+"""Graphviz figures, rendered by the ``dot`` binary."""
+from __future__ import annotations
+
+import re
+
+import markupsafe
+
+from .base import FigureError, plain_text
+
+
+ENGINES = ('dot', 'neato', 'fdp', 'circo', 'twopi')
+FORMATS = ('svg', 'png', 'pdf')
+
+#: attributes that make Graphviz read a file (or write a reference to one into the output)
+FILE_ATTRIBUTES = frozenset({'image', 'shapefile', 'imagepath', 'fontpath', 'fontnames',
+ 'stylesheet'})
+
+_IMG_TAG = re.compile(r'<\s*img\b', re.IGNORECASE)
+_ID_START = re.compile(r'[A-Za-z_\u0080-\U0010ffff]')
+_ID = re.compile(r'[\w\u0080-\U0010ffff]*')
+_NUMERAL = re.compile(r'-?(\.\d+|\d+(\.\d*)?)')
+
+
+def dot_escape(value) -> markupsafe.Markup:
+ """Make a text safe inside a double-quoted Graphviz name or label."""
+ text = plain_text(value)
+ text = text.replace('\\', '\\\\').replace('"', '\\"')
+ text = text.replace('\r\n', '\\n').replace('\n', '\\n').replace('\r', '\\n')
+ # Markup, so autoescape does not turn the source into HTML entities
+ return markupsafe.Markup(text) # noqa: S704 (escaped for the figure source above)
+
+
+def check_source(source: str):
+ """Refuse a source that references files, before Graphviz runs."""
+ tokens = _tokens(source)
+ for index, (kind, value) in enumerate(tokens):
+ if kind == 'html' and _IMG_TAG.search(value):
+ raise FigureError('graphviz', '
in an HTML-like label is not allowed')
+ if kind not in ('id', 'string') or index + 1 >= len(tokens) \
+ or tokens[index + 1] != ('op', '='):
+ continue
+ name = value.lower()
+ if name in FILE_ATTRIBUTES:
+ raise FigureError('graphviz', f'The "{value}" attribute is not allowed')
+ if name == 'fontname' and index + 2 < len(tokens) \
+ and re.search(r'[/\\]', tokens[index + 2][1]):
+ raise FigureError('graphviz', 'A file path as "fontname" is not allowed')
+
+
+def _tokens(source: str) -> list[tuple[str, str]]: # noqa: C901, PLR0912
+ """Split DOT source into identifiers, strings, HTML strings and operators."""
+ tokens: list[tuple[str, str]] = []
+ pos, size = 0, len(source)
+ line_start = True
+ while pos < size:
+ char = source[pos]
+ if char.isspace():
+ line_start = line_start or char == '\n'
+ pos += 1
+ continue
+ if char == '#' and line_start or source.startswith('//', pos):
+ end = source.find('\n', pos)
+ pos = size if end < 0 else end
+ continue
+ line_start = False
+ if source.startswith('/*', pos):
+ end = source.find('*/', pos + 2)
+ pos = size if end < 0 else end + 2
+ elif char == '"':
+ pos += 1
+ value = []
+ while pos < size and source[pos] != '"':
+ if source[pos] == '\\' and pos + 1 < size:
+ value.append(source[pos:pos + 2])
+ pos += 2
+ else:
+ value.append(source[pos])
+ pos += 1
+ pos += 1
+ tokens.append(('string', ''.join(value).replace('\\"', '"')))
+ elif char == '<':
+ depth, start = 0, pos
+ while pos < size:
+ if source[pos] == '<':
+ depth += 1
+ elif source[pos] == '>':
+ depth -= 1
+ if depth == 0:
+ break
+ pos += 1
+ tokens.append(('html', source[start + 1:pos]))
+ pos += 1
+ elif _ID_START.match(char):
+ match = _ID.match(source, pos)
+ end = match.end() if match else pos + 1
+ tokens.append(('id', source[pos:end]))
+ pos = max(end, pos + 1)
+ elif match := _NUMERAL.match(source, pos):
+ tokens.append(('id', match.group()))
+ pos = match.end()
+ else:
+ tokens.append(('op', char))
+ pos += 1
+ return tokens
+
+
+def args(engine: str, fmt: str) -> list[str]:
+ if engine not in ENGINES:
+ raise FigureError('graphviz',
+ f'Unknown engine "{engine}", use one of: {", ".join(ENGINES)}')
+ return [f'-K{engine}', f'-T{fmt}']
diff --git a/packages/dsw-templating/dsw/templating/figures/sanitize.py b/packages/dsw-templating/dsw/templating/figures/sanitize.py
new file mode 100644
index 00000000..bb465317
--- /dev/null
+++ b/packages/dsw-templating/dsw/templating/figures/sanitize.py
@@ -0,0 +1,330 @@
+"""The one gate for SVG output: an allow-list of elements, attributes and references.
+
+Every SVG a figure produces (Graphviz, d2, charts, the `svg` helper) passes through
+`sanitize_svg` before it is printed or stored. Anything not allowed is dropped. Every
+``id`` gets a per-figure prefix and every ``
+
+
+
+hi'''
+
+
+def test_sanitizer_drops_everything_not_allowed():
+ svg = sanitize_svg(HOSTILE_SVG, prefix='p-').decode()
+ for forbidden in ('script', 'foreignObject', 'onload', 'onclick', '@import', 'example.com',
+ 'file:', 'javascript', '' in svg
+ assert '#p-svg #p-g{fill:url(#p-g)}' in svg
+ assert 'href="data:image/png;base64,AAAA"' in svg and 'href="#p-g"' in svg
+ assert 'hi' in svg
+
+
+def test_svg_markup_does_not_depend_on_registered_namespaces(figures, monkeypatch):
+ # WeasyPrint registers the empty prefix when it is imported, after dsw.templating
+ import xml.etree.ElementTree as ET # noqa: PLC0415, S405
+ monkeypatch.setattr(ET, '_namespace_map', {**ET._namespace_map})
+ ET.register_namespace('', '')
+ svg = figures.svg.canvas(10, 10).svg
+ assert svg.startswith('',
+ prefix='p-').decode()
+ assert svg == ('')
+
+
+def test_sanitizer_keeps_a_nested_svg_that_scales():
+ svg = sanitize_svg(b'', prefix='p-').decode()
+ assert '' in svg
+
+
+def test_sanitizer_refuses_entities():
+ with pytest.raises(FigureError, match='entity'):
+ sanitize_svg(b']>',
+ prefix='p-')
+
+
+@needs_dot
+def test_two_copies_of_one_figure_do_not_share_ids(render):
+ html = _html(render('{% set f = "digraph { a }" %}{{ f|graphviz }}{{ f|graphviz }}'))
+ ids = re.findall(r' id="([^"]+)"', html)
+ assert len(ids) == len(set(ids)) > 2
+
+
+def test_figure_budget_per_document(render):
+ settings = RenderSettings(figures=FigureSettings(limits=FigureLimits(max_figures=2)))
+ source = '{% for i in range(N) %}{{ svg.canvas(10, 10) }}{% endfor %}'
+ assert _html(render(source.replace('N', '2'), settings=settings)).count(' b }', {'name': 'graphviz', 'options': {'format': 'svg'}})
+ assert document.file_format == FileFormats.SVG
+ assert document.filename('x') == 'x.svg' and document.content_type == 'image/svg+xml'
+ assert document.content.startswith(b'{{ "digraph { a -> b }"|graphviz }}{{ "x -> y"|d2 }}'
+ '{{ {"type": "bar", "labels": ["a"], "series": [{"values": [1]}]}|chart }}'
+ '{{ svg.canvas(10, 10) }}