Improve cuddly #1

Merged
hannaeko merged 8 commits from improve-cuddly into main 2026-11-16 22:58:43 +01:00
4 changed files with 100 additions and 240 deletions

163
.gitignore vendored
View file

@ -1,162 +1,9 @@
# ---> Python # Python
# Byte-compiled / optimized / DLL files
__pycache__/ __pycache__/
*.py[cod] build
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/ *.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/ env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
# Generated files
**/*.html
**/*.pdf

View file

@ -1,6 +1,6 @@
# Cuddly # Cuddly
Generate HTML and PDF from KDL structed data. Generate HTML and PDF files, with HTML and Jinja templates, from KDL structured data.
## Installation ## Installation
@ -11,7 +11,7 @@ python -m venv env
env/bin/pip install . env/bin/pip install .
``` ```
## Usage ## Basic Usage
### Example ### Example
@ -26,15 +26,31 @@ Generating a HTML file
env/bin/cuddly --template samples/cv/cv.template.html --input samples/cv.kdl --output samples/cv.html env/bin/cuddly --template samples/cv/cv.template.html --input samples/cv.kdl --output samples/cv.html
``` ```
### Template usage Generating both at the same time, with short options:
The template language used is [Jinja](https://jinja.palletsprojects.com/en/3.0.x/), source template need to be a single HTML template file. ```
env/bin/cuddly -t samples/cv/cv.template.html -i samples/cv.kdl -o samples/cv.pdf -o samples/cv.html
```
#### Base URL ### Samples
When generating the PDF the base URL is set to the source template directory. All relative links to other resources (for example CSS and images) must be relative to that directory. * `samples/cv/cv.template.html`: Template to generate a CV, see `samples/cv.kdl` for the input data.
* `samples/facture/facture.template.html`: Template to generate a French invoice, see `samples/facture.kdl` for the input data.
#### Accessing nodes values and attributes
## Template usage
The source template need to be a single HTML template file.
- The template language is [Jinja](https://jinja.palletsprojects.com/en/3.0.x/).
- For PDFs, the resulting HTML is run through [Weasyprint](https://weasyprint.org/).
- The data language is [KDL](https://kdl.dev/) (2.0.0).
### Base URL
When generating a PDF, the base URL is set to the source template directory. All relative links to other resources (for example CSS and images) must be relative to that directory.
### Accessing nodes values and attributes
Nodes are available as global variables in the template. The rendered value of a node is the first value that has been assigned to the node. This value can also be accessed using the `value` property. The list of values can be accessed using the `values` property. Nodes are available as global variables in the template. The rendered value of a node is the first value that has been assigned to the node. This value can also be accessed using the `value` property. The list of values can be accessed using the `values` property.
@ -56,7 +72,23 @@ something
something, other thing something, other thing
``` ```
Accessing children nodes can be done using properties of the children names. Attributes of a node can be accessed through the `attributes` property:
```kdl
my_node version=42 "something"
```
```jinja
{{ my_node.attributes.version }}
```
renders to
```
42
```
### Accessing children nodes
Children nodes can be accessed using the children names.
```kdl ```kdl
my_node { my_node {
@ -73,7 +105,7 @@ renders to
test test
``` ```
If a node has multiple children of a same node type, then directly accessing the children properties will fail, a loop will be needed. Note that, on the other hand, looping on the children always work, even if there is only one child of the given type. If a node has multiple children of a same node type, you’ll need to use a loop (directly accessing the children properties will fail). Note that, on the other hand, looping on the children always work, even if there is only one child of the given type.
```kdl ```kdl
my_node { my_node {
@ -85,7 +117,7 @@ my_node {
```jinja ```jinja
{% for node in my_node.other_node %} {% for node in my_node.other_node %}
{{ node.value }} {{ node.value }}
{% endofr %} {% endfor %}
``` ```
renders to renders to
@ -95,25 +127,11 @@ first
second second
``` ```
Attributes of a node can be accessed through the `attributes` property: ### Using components to template nodes
```kdl You can define node specific templates inside the `components` tag in the HTML template file. Nodes can then be rendered using those micro-templates using the `render` filter.
my_node version=42 "something"
```
```jinja The context of the micro-template is the node being rendered. As such, children and properties (`value`, `values`, `attributes`) of that node are in the global scope.
{{ my_node.attributes.version }}
```
renders to
```
42
```
#### Templating nodes
Node specific templates can be defined in the `components` element in the HTML template file. Nodes can then be rendered using those micro-templates using the `render` filter.
The context of the micro-template is the node being rendered. As such, children and properties of that node are in the global scope.
```kdl ```kdl
menu "Midnight meal" price="10 €" { menu "Midnight meal" price="10 €" {
@ -133,7 +151,7 @@ menu "Midnight meal" price="10 €" {
<h1>{{ value }}</h1> <h1>{{ value }}</h1>
<dl> <dl>
<dt>Price</dt> <dt>Price</dt>
<dd>{{ attributes.prices }}</dd> <dd>{{ attributes.price }}</dd>
</dl> </dl>
<dl> <dl>
@ -144,7 +162,7 @@ menu "Midnight meal" price="10 €" {
</menu> </menu>
<dish> <dish>
<div> <div>
<dt>{{ attribute.name }}</dt> <dt>{{ attributes.name }}</dt>
<dd>{{ value }}</dd> <dd>{{ value }}</dd>
</div> </div>
</dish> </dish>
@ -153,8 +171,3 @@ menu "Midnight meal" price="10 €" {
{{ menu | render }} {{ menu | render }}
</body> </body>
``` ```
## Samples
* `samples/cv/cv.template.html`: Template to generate a CV, see `samples/cv.kdl` for the input data.
* `samples/facture/facture.template.html`: Template to generate a French invoice, see `samples/facture.kdl` for the input data.

View file

@ -1,14 +1,15 @@
import sys
import pathlib import pathlib
from urllib.parse import urlparse from urllib.parse import urlparse
import kdl
import click import click
import kdl
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from bs4.element import Tag from bs4.element import Tag
from jinja2 import Environment from jinja2 import Environment
from weasyprint import HTML
class CuddlyMaybeList(object):
class CuddlyMaybeList:
""" """
If the given list is only one item behave like a proxy to that item. If the given list is only one item behave like a proxy to that item.
""" """
@ -36,43 +37,37 @@ class CuddlyMaybeList(object):
def __getitem__(self, key): def __getitem__(self, key):
return self.inner[key] return self.inner[key]
class CuddlyNode(object): class CuddlyNode:
""" """
Common interface to Document and Node. Common interface to Document and Node.
Provide helper method to render to HTMl. Provide helper method to render to HTMl.
Allow access to children nodes like object properties. Allow access to children nodes like object properties.
""" """
def __init__(self, inner): def __init__(self, kdl_node):
self.inner = inner self.name = getattr(kdl_node, 'name', None)
self.children = {}
for node in self.inner.nodes:
self.children.setdefault(node.name, [])
self.children[node.name].append(CuddlyNode(node))
self.children = {name: CuddlyMaybeList(nodes) for name, nodes in self.children.items()} self.values = []
self.attributes = {}
for entry in getattr(kdl_node, 'entries', []):
if entry[0] is None:
self.values.append(entry[1])
else:
self.attributes[entry[0]] = entry[1]
children = {}
for node in kdl_node.nodes:
children.setdefault(node.name, []).append(CuddlyNode(node))
self.children = {
name: CuddlyMaybeList(nodes) for name, nodes in children.items()
}
@property @property
def value(self): def value(self):
if args := getattr(self.inner, 'args', None): return next(iter(self.values), None)
return args[0]
else:
return None
@property
def values(self):
return getattr(self.inner, 'args', [])
@property
def attributes(self):
return getattr(self.inner, 'props', {})
@property
def name(self):
return getattr(self.inner, 'name', None)
def __getattr__(self, name): def __getattr__(self, name):
children = self.children[name] return self.children.get(name)
return children
def __str__(self): def __str__(self):
return str(self.value) return str(self.value)
@ -90,14 +85,17 @@ class CuddlyNode(object):
return template.render(variables) return template.render(variables)
class RenderNode(object): class RenderNode:
def __init__(self, components, env): def __init__(self, components, env):
self.components = components self.components = components
self.env = env self.env = env
def __call__(self, node): def __call__(self, node):
if isinstance(node, CuddlyMaybeList) and len(node) > 1: if isinstance(node, CuddlyMaybeList) and len(node) > 1:
raise Exception(f'Render filter must called be on single node, not list, got {type(node)}') raise Exception(
f'Cannot use `render` filter on list `{type(node)}`, '
+ 'use it on a single node instead'
)
if node.name in self.components: if node.name in self.components:
template = self.env.from_string(self.components[node.name]) template = self.env.from_string(self.components[node.name])
@ -115,10 +113,10 @@ def stripscheme(url):
return url[scheme_len:] return url[scheme_len:]
@click.command() @click.command()
@click.option('--template', help="Path to a template file") @click.option('-t', '--template', help="Path to a template file")
@click.option('--input', help="Path to a KDL file") @click.option('-i', '--input', help="Path to a KDL file")
@click.option('--output', help="Output file") @click.option('-o', '--output', 'outputs', help="Output file", multiple=True)
def main(template, input, output): def main(template, input, outputs):
""" """
Template a file using a KDL input Template a file using a KDL input
""" """
@ -126,12 +124,13 @@ def main(template, input, output):
with open(template_path) as template_file: with open(template_path) as template_file:
template_html = BeautifulSoup(template_file.read(), features="html.parser") template_html = BeautifulSoup(template_file.read(), features="html.parser")
components = template_html.components.extract() components = template_html.components.extract()
components = [element for element in components.children if isinstance(element, Tag)] components = [
element for element in components.children if isinstance(element, Tag)
]
template_string = template_html.decode() template_string = template_html.decode()
components = { components = {
component.name: component.decode_contents().strip() component.name: component.decode_contents().strip() for component in components
for component in components
} }
with open(input) as input_file: with open(input) as input_file:
@ -144,11 +143,12 @@ def main(template, input, output):
output_html = input_node.render(template) output_html = input_node.render(template)
if output.endswith('.pdf'): for output in outputs:
from weasyprint import HTML, default_url_fetcher if output.endswith('.pdf'):
base_dir = pathlib.Path(template_path).absolute().parent base_dir = pathlib.Path(template_path).absolute().parent
HTML(string=output_html, base_url=f'file://{base_dir}/').write_pdf(output, pdf_variant='pdf/ua-1') HTML(string=output_html, base_url=f'file://{base_dir}/').write_pdf(
output, pdf_variant='pdf/ua-1'
else: )
with open(output, 'w') as output_file: else:
output_file.write(output_html) with open(output, 'w') as output_file:
output_file.write(output_html)

View file

@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta"
version = "0.1" version = "0.1"
name = "cuddly" name = "cuddly"
dependencies = [ dependencies = [
"kdl-py==1.2.0", "kdl-py @ git+https://github.com/tabatkins/kdlpy@d9a220762fb9f55e4f59296256221084c26f54da",
"beautifulsoup4==4.12.3", "beautifulsoup4==4.12.3",
"Jinja2==3.1.3", "Jinja2==3.1.3",
"click==8.1.7", "click==8.1.7",