Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions .cspell/dictionary.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
7 changes: 7 additions & 0 deletions packages/dsw-document-worker/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
25 changes: 25 additions & 0 deletions packages/dsw-document-worker/config.example.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
62 changes: 62 additions & 0 deletions packages/dsw-document-worker/dsw/document_worker/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
ConfigKeys,
ConfigKeysContainer,
cast_bool,
cast_dict,
cast_float,
cast_int,
cast_optional_int,
cast_str,
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -266,6 +313,7 @@ class DocumentWorkerConfig:
log: LoggingConfig
doc: DocumentsConfig
pandoc: CommandConfig
figures: FiguresConfig
templates: TemplatesConfig
experimental: ExperimentalConfig
cloud: CloudConfig
Expand All @@ -288,6 +336,7 @@ def __str__(self):
f'{self.context}' \
f'{self.security}' \
f'Pandoc: {self.pandoc}' \
f'{self.figures}' \
f'====================\n'


Expand All @@ -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(
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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."""

Expand Down
25 changes: 24 additions & 1 deletion packages/dsw-document-worker/tests/test_templating.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from dsw.document_worker.config import (
CommandConfig,
FiguresConfig,
SecurityConfig,
TemplateConfig,
TemplateRequestsConfig,
Expand All @@ -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(
Expand All @@ -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 {},
),
)


Expand All @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions packages/dsw-tdk/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
13 changes: 13 additions & 0 deletions packages/dsw-templating/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
12 changes: 9 additions & 3 deletions packages/dsw-templating/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,17 @@ 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) |
| `docx` | the `pandoc-docx-pagebreakpy` Pandoc filter command (panflute) |
| `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

Expand Down Expand Up @@ -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)

Expand Down
Loading
Loading