API: support page with two Claude API clients, support and analyst (D-133)

Self-contained sub-project API/: a local support page where Marc pastes a
client's mail; a support agent and an analyst agent stay alive for the session
and produce a slide PDF that answers the client's question. Tools, detectors,
knowledge and Typst brand are copied (API/PROVENANCE.md). First real case:
Crissier (LENZSPITZE), workflow validated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
maximeandClaude Opus 5.5 committed 2026-11-05 12:58:39 +01:00
1 parent 874f6bf7ea
commit 8ba75b92fa
130 files changed
+42094

No files matched your search

+105
View File
@@ -0,0 +1,105 @@
# Changelog
Versions follow `MAJOR.MINOR.PATCH`: major when existing documents render
differently or stop compiling, minor for new helpers and options, patch for
fixes that do not change correct output.
## 1.1.0 — 2026-10-28
Brochure and presentation families brought to the level of the technical
family.
### Added
- Brochure: every page function is checked to fill exactly one page; a
cover rail that runs past the bottom margin or a page that runs onto the
next one gets a red overflow note in drafts and stops release builds.
- Overflows of every family leave an `<aimsight-overflow>` marker that
tests can query.
- `examples/brochure-specimen.typ`: cover, page types and every brochure
helper, built in the dark and light variants.
- `aim-red-on-dark` for red text on steel and deep slides.
- Tests: overflow fixtures for brochures and slides, every slide type in
every colour variant (`tests/slide_variants.py`), brochure and deck
translations in the factory test.
### Fixed
- The accent metric of `metric-slide` was red on steel (2.1:1 contrast);
it uses `aim-red-on-dark` on steel and deep slides.
- `company-address(style: "postal")` printed one line instead of two (the
brochure contact block and the closing slide).
- The slide overflow label was cut off at the left edge.
- Brochure and deck starters ignored `new.py --lang`; `new.py translate`
now works for every family, and the translation check compares
headings, brochure pages, slides, figures and tables.
## 1.0.0 — 2026-10-28
First frozen release. Based on the `aimsight_typst_final` bundle of
2026-09-21, imported unchanged as the first commit of this repository, then
reviewed (`docs/IMPROVEMENTS.md`). Compared with the bundle:
### Fixed
- Technical: `section-numbering: true` had no effect (the `set heading`
rule lived inside an `if` block).
- Technical: with a table of contents, the title page and the first body
page were both page 1; front matter is now numbered i, ii.
- Technical: the end-of-document address always moved to a new, otherwise
empty page. It now sits at the bottom of the last page and moves to the
bottom of one extra page only when it does not fit below the text
(footnotes included); `tests/end_address.py` checks 516 layouts.
- Technical: the running header followed the logical page counter; it now
hides on the first physical page only.
- Technical: paragraphs inside callouts and abstracts ran together; only
the first author was shown; PDF metadata was missing.
- Technical: a global rule turned every image into a centred full-width
block, so icons broke the line; figures centre, images keep their size.
- Presentation: the grey logo wordmark was below 3:1 contrast on steel and
deep slides; those slides use a white-wordmark logo.
- Logos are read relative to the theme, so the brand works from a vendored
`brand/` folder.
### Changed
- One official palette for every family (`docs/COLOR_SYSTEM.md`); reports
made with the v3 10/11 pt templates take it through the compat shim.
- `warning` callouts are orange, distinct from amber `caution` (ISO 3864 /
ANSI Z535 order caution < warning < danger).
- `logo: auto` / `none` mean the same in all families (the brochure used
`none` for "AIMsight logo").
- The company address, e-mail and web address come from
`theme/company.typ` in every template, with the country in the document
language.
- Inter 4.001 is bundled (`fonts/`, SIL OFL); builds use only the bundled
fonts, so every machine and CI runner renders the same glyphs.
- Minimum Typst version 0.14.0.
### Added
- Template wording in English, French, German, Spanish and Italian;
localised dates.
- Technical: `document-id`, `classification`, `approved-by`; `toc-depth`;
`revision-history()`; `data-table(...)`; `icon(...)`; `fig-row(...)`;
`screenshot(...)`; `summary-card(...)`; `todo[...]` and
`placeholder-figure(...)` (refused by release builds); `alt:` text on
pictures; `fig(...)` accepts content.
- Presentation: slide overflow is framed in red in drafts and refused in
releases; draft marker; closing-slide contact from the company block.
- Brochure: `lang`, `draft` mark, `website` default from the company block.
- `revision`, `date` and `draft` default to `auto`, stamped by the build
from git (semantic `v…` or letter `rev-…` tags, per document or global).
- `compat/legacy-conf.typ` for documents written against AIMsight.typ,
AIMsight_v2.typ, AIMsight_10pt.typ and AIMsight_11pt.typ.
- Starters (user manual, report, note, brochure, deck) and tools: build
(translations, release, PDF/A, watch), preview, lint (rules, budgets,
translations), new (documents and translations), docx2typ, capture
(DevTools engine), brand vendoring, release upload, CI setup.
- `examples/technical-specimen.typ`; `tests/run.py` end-to-end suite.
- `docs/LLM_AUTHORING.md`, `docs/ARCHITECTURE.md` and
`docs/COLOR_SYSTEM.md` rewritten for the factories.
### Removed
- `SOURCE_CHECK.txt` and `compile-examples.*` (replaced by `tests/run.py`).
+47
View File
@@ -0,0 +1,47 @@
a4717d5f3ec4c9df99c32c4583d2f7900d930cf03201e52be727c8be839cc22a assets/logos/AIMsight_logo_lg.svg
cf708862e748fbae94756bdb29e77b79cce32c7c61a173b551909c1e189a8232 assets/logos/AIMsight_logo_lg_reversed.svg
cb477a73f61c14d2e801cfcdd5a982d7c4a9e17b2d906c34f902e4a73750577f assets/logos/AIMsight_mark.svg
ba543321284ba0821a71b0216a4b30992c322aa2ffa4207f9059c46eff6e3050 CHANGELOG.md
3765e989a7f59d8374a7abb930a5e9c6a43790e18e477c95035054a644d1947f compat/legacy-conf.typ
a489d630dfa9f00ebdb3cfdfb351e0f7ac9a252ef026ea0d16ae31ff61bb0012 docs/ARCHITECTURE.md
ce4f00b17790a887a2b74690bd5138eb421e3723314e7f0876ff12f70921f05b docs/COLOR_SYSTEM.md
e4d0c29bd3cbced09455e62a65b7a9f4827a3ca2d46d088b9267c4aaac5bfb9f docs/IMPROVEMENTS.md
8191903dc937cca98e75045ecb0a778d9a744f5a1086af08f5f3ed3f2ca83286 docs/LLM_AUTHORING.md
b63214967512a7e22713385fe921ade8b28cdfc62141dd0fd6efae330d072396 docs/TEMPLATE_GUIDE.md
288316099b1e0a47a4716d159098005eef7c0066921f34e3200393dbdb01947f fonts/Inter-Bold.ttf
948405a16cdc62701da5f4005ed068ca5f4d27061d98f7974ccfc37831d9581d fonts/Inter-BoldItalic.ttf
1570cf7e75ce6ed1398359388e7daf8571cec3b8495ccaa46ddd64890c4c8eb4 fonts/Inter-Italic.ttf
97ad806f526e41546d46365bb3a393145f75b7b1568913db74549ad8b8dba872 fonts/Inter-Medium.ttf
66dd65b8125e4e7d6f0721216c647b5a3bc6fb236bfb1cef8c2c63a9bd53acd9 fonts/Inter-MediumItalic.ttf
40d692fce188e4471e2b3cba937be967878f631ad3ebbbdcd587687c7ebe0c82 fonts/Inter-Regular.ttf
78a843fade9d4612a5567302fb595b56976eb5fcebf4fea5a5912d638bafcde3 fonts/Inter-SemiBold.ttf
eff2930c3d3b35d3fcf5f76252b6baef4c3e907d9d2fde1d16cf5d417f8deef4 fonts/Inter-SemiBoldItalic.ttf
e7c0e5ee4146afff18acff63288e8630c11e300dff0d77ccafd0dc8fc2d88845 fonts/OFL.txt
788ed1b9fcd9d04201dbc2e6aa27f241eabdc29b35d3b713799a485c92455aa5 lib.typ
2a04d4ed8df6a9df2a17d6f1c40574a5841e22c9b7ecd20558f03607832adba0 README.md
7f17e4e5fdec8bc0375ec2d4c90bf1e92c26e748b958616cabb093b0cb174b5f starters/brochure/main.typ
81db4c1c5879db7787aadc75b04965d1b17d1eb64f3577067b34b17cf2fb934b starters/deck/main.typ
977670400d1de4d96346f7780ccbcc2330d6663e78793f299177505e641d37ae starters/note/main.typ
7aff10fa38a1e261b62ed104e866fbe0baaa7c73f695ceab07b3bbb1721334cb starters/report/main.typ
09649c97f4e051f0014ec9721b26273701f77a416dddcd525d4f49a914a048bf starters/user-manual/main.typ
d5b6e6b3ee06b68379a3bfabcf758d529fe3b9a67f21f94a8510eb4a98ce740e templates/brochure.typ
0065354bbefa2793248da2c965c606f089e854ab2635be43949de2ee396dc19e templates/presentation.typ
450be78692e75089033084003f5b7a1c9c0e09f12b5df26670b7ed37f07038fc templates/technical.typ
323036575905b5bc75c0edf64ddb72196e984508abbafd07a1906a1f8c727301 theme/colors.typ
be9f3f90cf64c8ba498a1a5baf9285599690bcc0ef22132d753eb86d2e689ae6 theme/company.typ
f4747f6965eb9e362825908a5545c8b630ff80a11241fb00a210c2113b3f563a theme/geometry.typ
c733aed6748981bb09bb0f3432fa3ef79043c226aed379a2479c84135d5433cb theme/i18n.typ
dc58b4f6561ce3408250317c1eb2eb825b083d8971fb16027d502255f4d187e7 theme/index.typ
1126a19cd5d7b28a64e2a87cfb76df89ecd5e6a484cdb9aee0bb2f33a05f954f theme/logo.typ
fcabebf079ec4f239ac91483ea69032f2baf7080a7c3db7ef3fbb1519985bbb1 theme/typography.typ
2331be8905e4e171d45d71bc74383ee358df4faa2528430051306ea1e78daf20 tools/brand.py
bb2dd75b699530f191c78830e539b40e4a5a6ef3cced6fe720d530c63e4f5db3 tools/build.py
e1b118a362a68573b51e8bd99812abe56fb32fa5b0c757027ca529c2b76ded57 tools/capture.py
882578161e7225ac420650bb2e55d103927673e2e4aef485dfee877308720614 tools/ci-setup.sh
f934d55fe490f7a62d5ad57ad201ffa027df629ac3f6c1ad0321971465834ce4 tools/docx2typ.py
7cd0e0660d64384bdf2179de6ef45efd78f4f1bacc63e583992be9839f3713b9 tools/lint.py
26a355348bbcffe253170e93054e09dcfaac2491a3f9bac06cedc6e1a79df3d9 tools/new.py
6744069497a0e4893f86e164ec9b58979eb1450213d30b746526cc55e4621fd1 tools/preview.py
3a7b97282ab1848a17c9f9c4e5a72c787c61767cfd485916611860d3e847c284 tools/release.py
dccfcb53270cc03e4a567412233e1e043e5ef1f636c01c5668b8495c2231fa28 typst.toml
1575e1af4a95f12f70b4ee6a6adce8160953d93ea17dc2611b90883ccc3ad3b8 VERSION
+72
View File
@@ -0,0 +1,72 @@
# AIMsight Typst brand
The company templates for AIMsight documents, frozen and versioned:
technical documents (manuals, FAQs, reports, notes), brochures and 16:9
presentations, with the Inter fonts and the toolkit the document factories
use to build, check, translate, import and illustrate documents.
**Writing a document? Do not start here.** Create a repository from one of
the document factories on Gitea; each carries a frozen copy of this brand in
`brand/`:
| Factory | For |
| --- | --- |
| `AIMsight/docfactory-technical` | user manuals, software documentation, FAQs, reports, notes; Word import and UI captures |
| `AIMsight/docfactory-brochure` | brochures, concept notes, datasheet-style leaflets |
| `AIMsight/docfactory-presentation` | slide decks |
This repository is where the brand itself changes, through pull requests and
version tags.
## Contents
- `templates/` — `technical.typ`, `brochure.typ`, `presentation.typ`: layout and public functions.
- `theme/` — colours, geometry, typography, logos, company identity, wording per language (en, fr, de, es, it).
- `fonts/` — Inter 4.001, eight static faces, SIL Open Font License (`fonts/OFL.txt`).
- `compat/legacy-conf.typ` — `conf(...)` for documents written against `AIMsight_v2.typ` / `AIMsight_10pt.typ` / `AIMsight_11pt.typ`: change the import line, nothing else.
- `starters/` — user-manual, report, note, brochure, deck.
- `tools/` — standard-library Python, run from a factory root:
- `build.py` lint, compile every document and translation, stamp revision/date/draft/history from git; `--release` for PDF/A; `--watch`
- `preview.py` live browser preview of every document
- `lint.py` authoring rules, text budgets, table headers, translation structure
- `new.py` new document from a starter; `new.py translate` for a language variant
- `docx2typ.py` Word document → draft technical document with its pictures
- `capture.py` UI screenshots from `captures.toml` (clicks, crops, hidden elements)
- `brand.py` vendor the brand into a factory, check it, update it to a tag
- `release.py`, `ci-setup.sh` used by the Gitea workflows
- `docs/TEMPLATE_GUIDE.md` — the public API, field guidance and text budgets. Start here.
- `docs/LLM_AUTHORING.md` — compile-safe Typst rules and a prompt for generated content.
- `docs/COLOR_SYSTEM.md`, `docs/ARCHITECTURE.md`, `docs/IMPROVEMENTS.md` (review record).
- `examples/` — canonical examples per family; `technical-specimen.typ` and `brochure-specimen.typ` show every helper of their family, `presentation-showcase.typ` every slide type.
- `tests/` — `run.py` (everything), `end_address.py`, `slide_variants.py`, `make_sample_docx.py`, smoke and overflow fixtures.
## Requirements
- Typst 0.14 or newer (tested with 0.14.2): `winget install --id Typst.Typst`
- Python 3.11+ for `tools/` and `tests/`
- Chrome or Edge for `capture.py` (nothing else to install)
- VS Code with Tinymist for live editing (recommended by `.vscode/extensions.json`)
## Check and preview
```bash
python tests/run.py # all checks; PDFs per document type in build/test-pdfs/
python tests/run.py --full # with the full end-of-document address sweep
python tools/preview.py --port 8771
```
In VS Code, the default build task runs the tests and Tinymist previews any
example with the bundled fonts. In the Claude Code desktop app,
`.claude/launch.json` (*brand-preview*) opens the preview in the browser pane.
## Changing the brand
1. Branch, change `theme/` or `templates/`, run `python tests/run.py` and look at the test PDFs that changed.
2. Add an entry to `CHANGELOG.md`; bump `VERSION`, `typst.toml` and `brand-version` in `lib.typ` (patch: fixes; minor: new helpers or options; major: existing documents render differently or stop compiling).
3. Open a pull request on Gitea; after merge, tag `vX.Y.Z` on main.
4. Factories and document repositories pick it up deliberately: `python brand/tools/brand.py update vX.Y.Z`, rebuild, review, commit. A document repository keeps its brand until its owner updates it, so an issued document always rebuilds identically.
The rule that keeps the documents uniform: **content files contain content
and semantic choices; the brand contains geometry, colours, typography,
spacing and page furniture.** `tools/lint.py` enforces it in the factories,
and `brand.py check` fails a build whose `brand/` copy was edited by hand.
+1
View File
@@ -0,0 +1 @@
1.1.0
@@ -0,0 +1,176 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
id="svg2"
version="1.1"
inkscape:version="1.2.2 (732a01da63, 2022-12-09)"
xml:space="preserve"
width="1060"
height="330"
viewBox="0 0 1060 330"
sodipodi:docname="AIMsight_logo_lg.svg"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/"><metadata
id="metadata8"><rdf:RDF><cc:Work
rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs
id="defs6"><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath16"><path
d="M 1.0729e-5,1.8311e-4 H 720.00001 V 405.00018 H 1.0729e-5 Z"
id="path18"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath28"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path30"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath40"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path42"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath52"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path54"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath64"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path66"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath76"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path78"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath88"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path90"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath100"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path102"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath112"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path114"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath124"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path126"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath136"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path138"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath148"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path150"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath160"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path162"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath172"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path174"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath></defs><sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="1600"
inkscape:window-height="838"
id="namedview4"
showgrid="false"
inkscape:zoom="0.41555556"
inkscape:cx="451.2032"
inkscape:cy="256.28342"
inkscape:window-x="2553"
inkscape:window-y="564"
inkscape:window-maximized="1"
inkscape:current-layer="g10"
inkscape:showpageshadow="2"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1" /><g
id="g10"
inkscape:groupmode="layer"
inkscape:label="AIMsight-20170105"
transform="matrix(1.25,0,0,-1.25,0,600)"><g
id="g132"
transform="translate(-80,-128)"><g
id="g134"
clip-path="url(#clipPath136)" /></g><g
id="g2458"
transform="translate(0,4.8)"><g
id="text140"
style="font-variant:normal;font-weight:bold;font-size:87.984px;font-family:Ebrima;-inkscape-font-specification:Ebrima-Bold;writing-mode:lr-tb;fill:#7f7f7f;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(2,0,0,-2,109.17543,263.85715)"><path
id="path4347"
d="M 61.219337,0 H 46.097087 L 41.715071,-13.704539 H 19.804992 L 15.465938,0 H 0.42960938 L 22.855219,-61.605985 H 39.309258 Z M 38.535961,-24.358852 31.919977,-45.066024 q -0.730336,-2.319891 -1.031063,-5.541961 h -0.343687 q -0.214805,2.706539 -1.074023,5.370117 l -6.701907,20.879016 z"
inkscape:connector-curvature="0" /><path
id="path4349"
d="m 86.434315,-61.605985 v 10.740234 h -5.155313 v 40.125516 h 5.155313 V 0 H 62.247306 v -10.740235 h 5.155313 v -40.125516 h -5.155313 v -10.740234 z"
inkscape:connector-curvature="0" /><path
id="path4351"
d="m 163.99599,0 h -13.70453 v -36.860485 q 0,-5.97157 0.51553,-13.189008 h -0.34369 q -1.07402,5.670844 -1.93324,8.162578 L 134.09518,0 h -11.34169 l -14.69264,-41.457305 q -0.60145,-1.675477 -1.93324,-8.592188 h -0.38665 q 0.55849,9.107719 0.55849,15.981469 V 0 H 93.797822 v -61.605985 h 20.320528 l 12.58755,36.516797 q 1.50363,4.382016 2.19101,8.806992 h 0.25776 q 1.15995,-5.112351 2.44878,-8.892914 L 144.191,-61.605985 h 19.80499 z"
inkscape:connector-curvature="0" /><path
id="path4353"
d="M 172.38059,-1.1599453 V -12.157945 q 3.35095,2.019164 6.65894,3.0072652 3.35096,0.9881016 6.31526,0.9881016 3.60872,0 5.67085,-0.9881016 2.10508,-0.9881012 2.10508,-3.0072652 0,-1.288829 -0.94514,-2.148047 -0.94514,-0.859219 -2.44877,-1.503633 -1.46067,-0.644414 -3.22207,-1.159946 -1.7614,-0.515531 -3.39392,-1.159945 -2.62061,-0.988101 -4.63978,-2.105086 -1.9762,-1.159945 -3.35095,-2.663578 -1.33179,-1.503633 -2.06213,-3.479836 -0.68737,-1.976203 -0.68737,-4.682742 0,-3.694641 1.58955,-6.358219 1.63252,-2.663578 4.2961,-4.339055 2.70654,-1.718437 6.14341,-2.491734 3.47984,-0.816258 7.21744,-0.816258 2.92134,0 5.92861,0.47257 3.00726,0.42961 5.92861,1.288828 v 10.482469 q -2.57766,-1.503633 -5.54196,-2.233968 -2.92135,-0.773297 -5.75677,-0.773297 -1.33179,0 -2.53469,0.257765 -1.15995,0.214805 -2.06213,0.687375 -0.90218,0.42961 -1.41771,1.159946 -0.51553,0.687375 -0.51553,1.589554 0,1.202907 0.77329,2.062125 0.7733,0.859219 2.01917,1.503633 1.24587,0.601453 2.7495,1.116985 1.54659,0.47257 3.05023,0.988101 2.70653,0.945141 4.89754,2.062125 2.19101,1.116985 3.7376,2.620617 1.58956,1.503633 2.40582,3.522797 0.85922,2.019164 0.85922,4.811625 0,3.9094457 -1.71844,6.7019067 -1.67548,2.7495001 -4.5109,4.5108985 -2.79246,1.71843754 -6.4871,2.49173443 -3.65168,0.81625787 -7.60409,0.81625787 -7.2604,0 -13.44677,-2.2339688 z"
inkscape:connector-curvature="0" /><path
id="path4355"
d="m 219.34996,-50.951673 q -3.43687,0 -5.62788,-2.019164 -2.19101,-2.062125 -2.19101,-5.026429 0,-3.050227 2.19101,-4.983469 2.19101,-1.933242 5.62788,-1.933242 3.47984,0 5.62788,1.933242 2.19101,1.933242 2.19101,4.983469 0,3.093187 -2.19101,5.06939 -2.14804,1.976203 -5.62788,1.976203 z M 226.05187,0 h -13.57566 v -43.992001 h 13.57566 z"
inkscape:connector-curvature="0" /><path
id="path4357"
d="m 279.10072,-5.0264298 q 0,12.2438674 -7.08855,18.9457738 -7.08856,6.744867 -20.53533,6.744867 -8.89292,0 -14.09119,-2.534695 V 6.7019063 q 6.78783,3.9524067 13.70454,3.9524067 6.87375,0 10.65431,-3.6516801 3.78057,-3.6087188 3.78057,-9.8380548 v -3.479836 h -0.17185 q -4.63978,7.3892814 -13.70454,7.3892814 -8.42034,0 -13.36085,-5.9286095 -4.94051,-5.928609 -4.94051,-15.895547 0,-11.169844 5.499,-17.742868 5.499,-6.573023 14.47784,-6.573023 8.03369,0 12.02906,6.186375 h 0.17185 v -5.112352 h 13.57565 z M 265.69691,-21.136782 v -3.479836 q 0,-4.167211 -2.49174,-7.088554 -2.44877,-2.964305 -6.40118,-2.964305 -4.51089,0 -7.08855,3.522797 -2.57766,3.522797 -2.57766,9.923977 0,5.499 2.44878,8.72107 2.44877,3.1791094 6.7019,3.1791094 4.21018,0 6.78783,-3.2220704 2.62062,-3.265031 2.62062,-8.592188 z"
inkscape:connector-curvature="0" /><path
id="path4359"
d="m 331.25288,0 h -13.5327 v -25.003266 q 0,-9.666211 -7.04559,-9.666211 -3.60872,0 -5.84269,2.706539 -2.23397,2.706539 -2.23397,6.87375 V 0 h -13.57565 v -65.128782 h 13.57565 v 27.666844 h 0.17185 q 4.98347,-7.604086 13.53269,-7.604086 14.95041,0 14.95041,18.043594 z"
inkscape:connector-curvature="0" /><path
id="path4361"
d="m 367.08574,-0.51553126 q -3.00727,1.58955476 -9.06476,1.58955476 -14.34895,0 -14.34895,-14.9074455 v -20.14868 h -7.13152 v -10.009899 h 7.13152 v -9.494367 l 13.53269,-3.866484 v 13.360851 h 9.88102 v 10.009899 h -9.88102 v 17.785828 q 0,6.8737504 5.45604,6.8737504 2.14805,0 4.42498,-1.2458674 z"
inkscape:connector-curvature="0" /></g><g
transform="matrix(2,0,0,2,-205.96457,-164.12285)"
id="g168"><g
clip-path="url(#clipPath172)"
id="g170"><g
id="text176"
style="font-variant:normal;font-weight:bold;font-size:140.09px;font-family:Ebrima;-inkscape-font-specification:Ebrima-Bold;writing-mode:lr-tb;fill:#e41d25;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,100.7,213.91)"><path
id="path4310"
d="m 59.100467,-72.028694 -18.742509,2.530922 13.40705,14.433101 -12.449404,8.550414 -9.371254,-17.374443 -9.371255,17.374443 -12.517807,-8.550414 13.475454,-14.433101 -18.7425097,-2.530922 4.8566356,-13.817471 17.2376361,7.387559 -2.941343,-19.631753 h 16.006377 l -2.941343,19.631753 17.10083,-7.387559 z"
inkscape:connector-curvature="0" /></g></g></g></g></g></svg>

After

Width:  |  Height:  |  Size: 11 KiB

@@ -0,0 +1,176 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
id="svg2"
version="1.1"
inkscape:version="1.2.2 (732a01da63, 2022-12-09)"
xml:space="preserve"
width="1060"
height="330"
viewBox="0 0 1060 330"
sodipodi:docname="AIMsight_logo_lg.svg"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/"><metadata
id="metadata8"><rdf:RDF><cc:Work
rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs
id="defs6"><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath16"><path
d="M 1.0729e-5,1.8311e-4 H 720.00001 V 405.00018 H 1.0729e-5 Z"
id="path18"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath28"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path30"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath40"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path42"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath52"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path54"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath64"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path66"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath76"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path78"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath88"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path90"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath100"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path102"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath112"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path114"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath124"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path126"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath136"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path138"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath148"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path150"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath160"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path162"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath><clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath172"><path
d="M 1.0729e-5,0 H 720.00001 V 405 H 1.0729e-5 Z"
id="path174"
inkscape:connector-curvature="0"
style="clip-rule:evenodd" /></clipPath></defs><sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="1600"
inkscape:window-height="838"
id="namedview4"
showgrid="false"
inkscape:zoom="0.41555556"
inkscape:cx="451.2032"
inkscape:cy="256.28342"
inkscape:window-x="2553"
inkscape:window-y="564"
inkscape:window-maximized="1"
inkscape:current-layer="g10"
inkscape:showpageshadow="2"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1" /><g
id="g10"
inkscape:groupmode="layer"
inkscape:label="AIMsight-20170105"
transform="matrix(1.25,0,0,-1.25,0,600)"><g
id="g132"
transform="translate(-80,-128)"><g
id="g134"
clip-path="url(#clipPath136)" /></g><g
id="g2458"
transform="translate(0,4.8)"><g
id="text140"
style="font-variant:normal;font-weight:bold;font-size:87.984px;font-family:Ebrima;-inkscape-font-specification:Ebrima-Bold;writing-mode:lr-tb;fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(2,0,0,-2,109.17543,263.85715)"><path
id="path4347"
d="M 61.219337,0 H 46.097087 L 41.715071,-13.704539 H 19.804992 L 15.465938,0 H 0.42960938 L 22.855219,-61.605985 H 39.309258 Z M 38.535961,-24.358852 31.919977,-45.066024 q -0.730336,-2.319891 -1.031063,-5.541961 h -0.343687 q -0.214805,2.706539 -1.074023,5.370117 l -6.701907,20.879016 z"
inkscape:connector-curvature="0" /><path
id="path4349"
d="m 86.434315,-61.605985 v 10.740234 h -5.155313 v 40.125516 h 5.155313 V 0 H 62.247306 v -10.740235 h 5.155313 v -40.125516 h -5.155313 v -10.740234 z"
inkscape:connector-curvature="0" /><path
id="path4351"
d="m 163.99599,0 h -13.70453 v -36.860485 q 0,-5.97157 0.51553,-13.189008 h -0.34369 q -1.07402,5.670844 -1.93324,8.162578 L 134.09518,0 h -11.34169 l -14.69264,-41.457305 q -0.60145,-1.675477 -1.93324,-8.592188 h -0.38665 q 0.55849,9.107719 0.55849,15.981469 V 0 H 93.797822 v -61.605985 h 20.320528 l 12.58755,36.516797 q 1.50363,4.382016 2.19101,8.806992 h 0.25776 q 1.15995,-5.112351 2.44878,-8.892914 L 144.191,-61.605985 h 19.80499 z"
inkscape:connector-curvature="0" /><path
id="path4353"
d="M 172.38059,-1.1599453 V -12.157945 q 3.35095,2.019164 6.65894,3.0072652 3.35096,0.9881016 6.31526,0.9881016 3.60872,0 5.67085,-0.9881016 2.10508,-0.9881012 2.10508,-3.0072652 0,-1.288829 -0.94514,-2.148047 -0.94514,-0.859219 -2.44877,-1.503633 -1.46067,-0.644414 -3.22207,-1.159946 -1.7614,-0.515531 -3.39392,-1.159945 -2.62061,-0.988101 -4.63978,-2.105086 -1.9762,-1.159945 -3.35095,-2.663578 -1.33179,-1.503633 -2.06213,-3.479836 -0.68737,-1.976203 -0.68737,-4.682742 0,-3.694641 1.58955,-6.358219 1.63252,-2.663578 4.2961,-4.339055 2.70654,-1.718437 6.14341,-2.491734 3.47984,-0.816258 7.21744,-0.816258 2.92134,0 5.92861,0.47257 3.00726,0.42961 5.92861,1.288828 v 10.482469 q -2.57766,-1.503633 -5.54196,-2.233968 -2.92135,-0.773297 -5.75677,-0.773297 -1.33179,0 -2.53469,0.257765 -1.15995,0.214805 -2.06213,0.687375 -0.90218,0.42961 -1.41771,1.159946 -0.51553,0.687375 -0.51553,1.589554 0,1.202907 0.77329,2.062125 0.7733,0.859219 2.01917,1.503633 1.24587,0.601453 2.7495,1.116985 1.54659,0.47257 3.05023,0.988101 2.70653,0.945141 4.89754,2.062125 2.19101,1.116985 3.7376,2.620617 1.58956,1.503633 2.40582,3.522797 0.85922,2.019164 0.85922,4.811625 0,3.9094457 -1.71844,6.7019067 -1.67548,2.7495001 -4.5109,4.5108985 -2.79246,1.71843754 -6.4871,2.49173443 -3.65168,0.81625787 -7.60409,0.81625787 -7.2604,0 -13.44677,-2.2339688 z"
inkscape:connector-curvature="0" /><path
id="path4355"
d="m 219.34996,-50.951673 q -3.43687,0 -5.62788,-2.019164 -2.19101,-2.062125 -2.19101,-5.026429 0,-3.050227 2.19101,-4.983469 2.19101,-1.933242 5.62788,-1.933242 3.47984,0 5.62788,1.933242 2.19101,1.933242 2.19101,4.983469 0,3.093187 -2.19101,5.06939 -2.14804,1.976203 -5.62788,1.976203 z M 226.05187,0 h -13.57566 v -43.992001 h 13.57566 z"
inkscape:connector-curvature="0" /><path
id="path4357"
d="m 279.10072,-5.0264298 q 0,12.2438674 -7.08855,18.9457738 -7.08856,6.744867 -20.53533,6.744867 -8.89292,0 -14.09119,-2.534695 V 6.7019063 q 6.78783,3.9524067 13.70454,3.9524067 6.87375,0 10.65431,-3.6516801 3.78057,-3.6087188 3.78057,-9.8380548 v -3.479836 h -0.17185 q -4.63978,7.3892814 -13.70454,7.3892814 -8.42034,0 -13.36085,-5.9286095 -4.94051,-5.928609 -4.94051,-15.895547 0,-11.169844 5.499,-17.742868 5.499,-6.573023 14.47784,-6.573023 8.03369,0 12.02906,6.186375 h 0.17185 v -5.112352 h 13.57565 z M 265.69691,-21.136782 v -3.479836 q 0,-4.167211 -2.49174,-7.088554 -2.44877,-2.964305 -6.40118,-2.964305 -4.51089,0 -7.08855,3.522797 -2.57766,3.522797 -2.57766,9.923977 0,5.499 2.44878,8.72107 2.44877,3.1791094 6.7019,3.1791094 4.21018,0 6.78783,-3.2220704 2.62062,-3.265031 2.62062,-8.592188 z"
inkscape:connector-curvature="0" /><path
id="path4359"
d="m 331.25288,0 h -13.5327 v -25.003266 q 0,-9.666211 -7.04559,-9.666211 -3.60872,0 -5.84269,2.706539 -2.23397,2.706539 -2.23397,6.87375 V 0 h -13.57565 v -65.128782 h 13.57565 v 27.666844 h 0.17185 q 4.98347,-7.604086 13.53269,-7.604086 14.95041,0 14.95041,18.043594 z"
inkscape:connector-curvature="0" /><path
id="path4361"
d="m 367.08574,-0.51553126 q -3.00727,1.58955476 -9.06476,1.58955476 -14.34895,0 -14.34895,-14.9074455 v -20.14868 h -7.13152 v -10.009899 h 7.13152 v -9.494367 l 13.53269,-3.866484 v 13.360851 h 9.88102 v 10.009899 h -9.88102 v 17.785828 q 0,6.8737504 5.45604,6.8737504 2.14805,0 4.42498,-1.2458674 z"
inkscape:connector-curvature="0" /></g><g
transform="matrix(2,0,0,2,-205.96457,-164.12285)"
id="g168"><g
clip-path="url(#clipPath172)"
id="g170"><g
id="text176"
style="font-variant:normal;font-weight:bold;font-size:140.09px;font-family:Ebrima;-inkscape-font-specification:Ebrima-Bold;writing-mode:lr-tb;fill:#e41d25;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,100.7,213.91)"><path
id="path4310"
d="m 59.100467,-72.028694 -18.742509,2.530922 13.40705,14.433101 -12.449404,8.550414 -9.371254,-17.374443 -9.371255,17.374443 -12.517807,-8.550414 13.475454,-14.433101 -18.7425097,-2.530922 4.8566356,-13.817471 17.2376361,7.387559 -2.941343,-19.631753 h 16.006377 l -2.941343,19.631753 17.10083,-7.387559 z"
inkscape:connector-curvature="0" /></g></g></g></g></g></svg>

After

Width:  |  Height:  |  Size: 11 KiB

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="54.5" height="52" viewBox="0 0 54.5 52">
<path fill="#E41D25" transform="translate(-4.7878 98.0904)"
d="m 59.100467,-72.028694 -18.742509,2.530922 13.40705,14.433101 -12.449404,8.550414 -9.371254,-17.374443 -9.371255,17.374443 -12.517807,-8.550414 13.475454,-14.433101 -18.7425097,-2.530922 4.8566356,-13.817471 17.2376361,7.387559 -2.941343,-19.631753 h 16.006377 l -2.941343,19.631753 17.10083,-7.387559 z"/>
</svg>

After

Width:  |  Height:  |  Size: 475 B

@@ -0,0 +1,64 @@
// ============================================================================
// Migration shim for documents written against the pre-1.0 templates:
// AIMsight.typ / AIMsight_v2.typ (Exo 2, 12 pt, Pandoc-derived `conf`)
// AIMsight_10pt.typ / AIMsight_11pt.typ (v3 light technical template)
//
// Replace the old import line with
// #import "/brand/compat/legacy-conf.typ": *
// and the document renders with the current technical template. New documents
// should use `technical-document(...)` from templates/technical.typ directly.
//
// Mapping decisions:
// - `font` is ignored: the brand font is Inter (theme/typography.typ).
// - `fontsize` >= 11pt selects density "standard", otherwise "compact".
// - `logo` paths such as "AIMsight_logo_lg.svg" are ignored: the brand logo
// is used unless `logo: none` is given.
// - `sectionnumbering: none` and `false` both disable numbering.
// ============================================================================
#import "../templates/technical.typ": *
#let conf(
title: none,
subtitle: none,
authors: ((name: [AIMsight]),),
date: auto,
revision: auto,
venue: none,
abstract: none,
document_label: none,
lang: "en",
region: "CH",
font: none,
fontsize: 10pt,
justify_text: false,
sectionnumbering: true,
showtoc: true,
pagebreak_before_toc: false,
logo: auto,
show_address: true,
address: auto,
doc,
) = {
let extra = if address == auto { (:) } else { (address: address) }
technical-document(
title: title,
subtitle: subtitle,
authors: authors,
date: date,
revision: revision,
venue: venue,
abstract: abstract,
document-label: document_label,
lang: lang,
region: region,
density: if fontsize >= 11pt { "standard" } else { "compact" },
justify-text: justify_text,
section-numbering: sectionnumbering == true,
show-toc: showtoc,
pagebreak-before-toc: pagebreak_before_toc,
logo: if logo == none { none } else { auto },
show-address: show_address,
..extra,
doc,
)
}
@@ -0,0 +1,89 @@
# AIMsight Typst architecture
## Goal
Every AIMsight document (manuals, FAQs, reports, notes, brochures, slide
decks) looks like one company wrote it, can be rebuilt identically from git
years later, and can be written or migrated with automation (Word import,
UI captures, LLM drafting) without anyone touching layout.
## Repositories
```
AIMsight/aimsight-typst the brand (this repository): templates, theme, fonts,
tools, starters, tests; released as tags vX.Y.Z
AIMsight/docfactory-technical template repositories colleagues start from; each holds
AIMsight/docfactory-brochure a frozen copy of one brand release in brand/ plus a
AIMsight/docfactory-presentation starter document, editor/CI configuration and README
<team>/<document set> created from a factory with "Use this template";
documents/<slug>/main.typ (+ main.<lang>.typ)
```
The brand is **vendored**, not referenced: `tools/brand.py install` copies
the files documents need into `brand/` with a SHA-256 manifest. A document
repository therefore builds offline, in CI without credentials, and with
the exact brand it was released with; `brand.py check` fails the build when
`brand/` was edited by hand, and `brand.py update <tag>` moves a repository
to a newer brand deliberately.
## Separation of concerns
- `theme/` holds the design decisions: colours, geometry, typography, logo
loading, company identity, template wording per language.
- `templates/` holds layout logic and the public functions of the three
families.
- Documents hold content and semantic choices only. `tools/lint.py`
enforces it (no positioning, colours, fonts or page settings; text
budgets; table headers; translation structure).
Path rule: string paths given to template helpers are resolved from
`brand/templates/`, so documents use root paths (`/documents/<slug>/...`)
or pass `image(...)` content. Logos are read relative to `theme/logo.typ`,
so the brand works from any folder.
## Families
**Technical** (`technical-document`): flow-based A4 for manuals, FAQs,
reports and notes; compact or standard density; document control fields;
contents with roman front matter; callouts by severity; figures, picture
rows, screenshots, icons, data tables, summary cards, revision history,
drafting markers; the company address at the bottom of the last page.
**Brochure** (`brochure`, `brochure-cover`, `brochure-page`,
`brochure-final-page`): one canonical cover grammar (former
`brochure-cover-concept-last`) in a dark or light variant, standard content
pages with a structured right rail; each page function fills exactly one
page and overflow is flagged in drafts and refused in releases.
**Presentation** (`presentation` plus one function per slide type): 16:9,
variants `light`, `steel` and `deep`; no hidden state; overflowing slides
are flagged in drafts and refused in releases.
## Build and release
`tools/build.py` compiles `documents/*/main*.typ` with the bundled fonts
only and stamps each PDF from git: revision (`<doc>/v1.2.0`,
`<doc>/rev-B` or global tags), date (tag date for releases), DRAFT mark and
the revision history. `--release` additionally requires a clean tagged
tree, refuses `#todo`, placeholders and slide overflow, and writes PDF/A-2b.
The factory workflow (`.gitea/workflows/build.yml`) builds every pull
request and attaches release PDFs to the Gitea release of a tag.
## Automation
- `tools/docx2typ.py`: Word → draft technical document (headings, lists,
tables, pictures, captions, footnotes, callouts), with a review list of
what needs a human look.
- `tools/capture.py`: UI screenshots from `captures.toml` through Chrome's
DevTools protocol (clicks, form input, hidden elements, element crops,
full pages) or Playwright.
- `tools/preview.py`: live browser preview of every document and language.
- `docs/LLM_AUTHORING.md`: rules and a prompt for generated content.
## Tests
`tests/run.py` builds every example and smoke test, every starter in a
throwaway factory (including a translation), a generated Word document,
a tagged PDF/A release, the end-of-document address sweep, captures on a
local test page and the preview server, and leaves one PDF per document
type in `build/test-pdfs/`. The brand CI runs it on every push.
@@ -0,0 +1,62 @@
# AIMsight colour system
One palette for brochures, technical documents and presentations, defined
once in `theme/colors.typ`. Documents never use colour values; they use the
names below through the templates. AIMsight red stays scarce and semantic.
## Brand palette (official from brand 1.0.0)
| Token | Hex | Role |
| --- | --- | --- |
| `aim-red` | `#E41D25` | AIMsight mark, monitored point, alarm/exception, danger callouts; rare high-priority cue |
| `aim-red-on-dark` | `#FF6B6F` | the same cue as text on steel and deep slides (3.5:1 on steel, 5.8:1 on slide-deep; `#E41D25` falls to 2.1:1 there) |
| `ink` | `#252D33` | primary text on light backgrounds |
| `graphite` | `#39434A` | secondary dark text |
| `steel` | `#074A5E` | primary branded teal: headings level 2, brochure title band, title slides, classification marks |
| `data-steel` | `#5992AD` | secondary data/metadata accent, running-header label |
| `deep-steel` | `#023D51` | brochure dark rail |
| `slide-deep` | `#10232D` | deliberately darker presentation section/quote background |
| `cloud` | `#F4F7F8` | quiet technical fill: notes, data-table headers, abstract |
| `rule` | `#B8CDD5` | light rules and dividers |
| `quiet` | `#657980` | captions and metadata |
The presentation `deep` variant is intentionally darker than the `steel`
title-slide background, so title and section slides are clearly different.
On `steel` and `deep` slides the logo uses its white wordmark
(`assets/logos/AIMsight_logo_lg_reversed.svg`): the grey wordmark is below
3:1 contrast there.
## Safety and status colours (technical family)
Callouts follow the ISO 3864 / ANSI Z535 order of severity. Each label
colour reaches at least 4.2:1 on white.
| Callout | Accent / label | Fill | Meaning |
| --- | --- | --- | --- |
| `note` | `rule` / `steel` | `cloud` | background information |
| `tip` | `data-steel` / `steel` | `tip-fill` `#EAF4F7` | good practice |
| `caution` | `amber` `#A96F18` | `amber-fill` `#FFF8E8` | risk of a wrong measurement or minor damage |
| `warning` | `orange` `#C2560F` | `orange-fill` `#FFF3EA` | risk of serious damage, data loss or injury |
| `danger` | `aim-red` | `danger-fill` `#FFF1F2` | immediate risk of death or serious injury |
`zebra-fill` `#F9FBFB` stripes long data tables; `todo` markers use amber.
## Decision: one palette for every document
Before 1.0 the technical reports used a different palette
(`AIMsight_10pt.typ` / `AIMsight_11pt.typ`, "v3"). Brand 1.0.0 makes the
palette above the only one; reports built with the compatibility shim
(`compat/legacy-conf.typ`) or migrated to `technical-document` take it
automatically. Old to new:
| v3 report token | v3 hex | 1.0 token | 1.0 hex |
| --- | --- | --- | --- |
| `ink` | `#20262A` | `ink` | `#252D33` |
| `steel` | `#315B68` | `steel` | `#074A5E` |
| `steel_soft` | `#5F8791` | `data-steel` | `#5992AD` |
| `cloud` | `#F4F6F6` | `cloud` | `#F4F7F8` |
| `rule` | `#DCE2E3` | `rule` | `#B8CDD5` |
| `quiet` | `#6F7A7E` | `quiet` | `#657980` |
Changing a value in `theme/colors.typ` is a brand change: pull request,
changelog entry, new tag.
@@ -0,0 +1,49 @@
# Review record: from the bundle to brand 1.0.0
The `aimsight_typst_final` bundle (2026-09-21) was frozen as brand 1.0.0
after a review against the existing documents (registration-metrics note,
Pont des Planches report, station manual and FAQ in three languages,
acquisition modes, camera motion compensation, CAM Word guides, dashboard
guide). All proposals were accepted on 2026-10-28 and are in 1.0.0; this
file records what was decided and where it lives.
| # | Proposal | Decision / implementation |
| --- | --- | --- |
| 1 | One palette | The bundle palette is official; v3 report colours mapped in `COLOR_SYSTEM.md` |
| 2 | Distinct warning colour | `warning` orange `#C2560F`, `caution` amber, `danger` red |
| 3 | Revision letters | `<doc>/rev-A` tags → "Revision A"; `#revision-history()` from tags; release date = tag date |
| 4 | Document control | `document-id`, `classification`, `approved-by` on page 1 and in every footer |
| 5 | Bundle Inter | `fonts/` (8 static faces, OFL); builds ignore system fonts |
| 6 | Image centring rule | Removed; figures centre, `icon(...)` for inline pictures |
| 7 | Tables over page breaks | `data-table(...)` with repeating shaded header; lint flags bold first rows |
| 8 | One company block | `theme/company.typ`, used by all templates |
| 9 | Logo semantics | `auto` / `none` everywhere |
| 10 | Localised dates | `format-date` in `theme/i18n.typ` (en, fr, de, es, it) |
| 11 | Contents depth | `toc-depth`, compact contents styling |
| 12 | Slide overflow | Red frame in drafts, error in releases |
| 13 | Text budgets | `lint.py` warns on the budgets of `TEMPLATE_GUIDE.md` |
| 14 | Accessible, archivable PDFs | `alt:` on pictures; releases are PDF/A-2b |
| 15 | Captures from the real application | `capture.py` DevTools engine: clicks, form input, hidden elements, crops, full page |
| 16 | Gitea | Factories as template repositories; Actions workflows for brand and factories |
| 17 | Compiler floor | 0.14.0 (tested 0.14.2) |
| 18 | Retire duplicates | CAM quick start guide (Word) retired; station manual v1.5 is the reference |
End-of-document address: the intent is that the address always sits at the
bottom of the last page, adding a nearly empty page when needed. The bundle
always added a page; 1.0.0 adds one only when the address does not fit
below the text, and never lets a footnote push the address to the top of a
page (`tests/end_address.py`).
## 1.1.0: family parity
The brochure and presentation families were brought to the technical
family's level: brochure specimen in both variants, one-page overflow checks
for brochure pages and covers, tested slide overflow, every slide type in
every variant, translations for all families, and a readable accent red on
dark slides.
## Open for later versions
- Tagged PDF/UA output once every picture in the documents has alt text.
- Sharing captures between document repositories when several manuals show
the same application.
@@ -0,0 +1,81 @@
# Compile-safe Typst for generated AIMsight documents
Rules for content written or rewritten by an LLM (or converted by
`tools/docx2typ.py`). They complement section 5 of `TEMPLATE_GUIDE.md`, which
says *which* functions to use; this file says how to write Typst that compiles
the first time. Origin: the `typst-compile-safe-skill.md` used for the
registration-metrics note, generalised for every document.
Paste the prompt at the end into the assistant, together with
`TEMPLATE_GUIDE.md` and the starter document of the factory.
## Document header
Keep the `#show: technical-document.with(...)` block of the starter document.
Change only `title`, `subtitle`, `document-label`, `authors`, `lang`,
`density` and `show-toc`. Do not set `revision`, `date` or `draft`: the build
stamps them from git.
## Markup
- Use `-` for every bullet item and `1.` / `+` for numbered items. Never use `*` as a list marker.
- Use `#strong[...]` for bold and `#emph[...]` for italics, not `*...*` / `_..._`.
- Escape literal `#`, `$`, `@`, `<`, `*`, `_` in prose with a backslash (`info\@aimsight.ch`).
- Keep every opening delimiter paired: `[ ]`, `( )`, `{ }`, `$ $`, code fences.
- Use plain Typst, never LaTeX commands (`\textbf`, `\frac`, `\begin{...}`).
- Pictures: `#fig("/documents/<doc>/images/x.png", caption: [...], alt: "...")`; side by side: `#fig-row(...)`; UI captures: `#screenshot("/captures/x.png", caption: [...])`; inline: `#icon(...)`.
- Translations live in `main.<lang>.typ` next to `main.typ`: translate the text, keep every heading, label and picture in the same order.
## Math
- Inline math: `$x$`. Display math has spaces inside the dollars: `$ x^2 + y^2 = r^2 $`.
- Prefer single-letter variables. Quote multi-letter labels: `A_"ref"`, `S_"med"`, `tau_"zero"`.
- Group label-plus-index subscripts with parentheses: `S_("width", t)`, `D_("L", t)(y)`.
- For a fixed compound label use one quoted hyphenated label: `A_"seg-ref"`. Avoid commas inside quoted labels.
- Named operators: `op("median")`, `op("mean")`, `op("std")`, `op("argmax")`; limits below with `op("median", limits: #true)_(p in Omega)`.
- Prefer Typst-native functions: `abs(x)`, `sqrt(x)`, `frac(a, b)`, `ln(x)`, `exp(x)`, `bb(1)[condition]`.
- Avoid untested names (`conj`, `real`, `det`, `trace`) and `cap` / `cup`; rewrite overlaps with indicator sums.
- When complex or matrix notation is not essential, define the quantity in prose and give the scalar formula used in practice.
Patterns known to compile:
```typst
$ A_("seg", t) = sum_(p in Omega) m_t(p) b_("seg", t)(p) $
$ D_("A-seg", t) = frac(abs(A_("seg", t) - A_"seg-ref"), A_"seg-ref" + epsilon) $
$ s_("sat", t) = frac(1, n) sum_(p in Omega) bb(1)[i_t(p) >= i_"sat"] $
```
## Tables
- Prefer `#data-table(columns: ..., header: (...), ...)`: shaded header that repeats after page breaks.
- Close every cell with `]`; keep math in its own cell; avoid long nested markup in cells.
- Do not set `stroke`, `inset` or `fill` on tables: the template styles them.
```typst
#data-table(
columns: (1.5fr, 1.5fr, 3fr),
header: ([Metric], [Purpose], [Interpretation]),
[$e_t$], [Appearance consistency], [General loss of reference/current correspondence.],
)
```
## Before handing back
Run `python brand/tools/build.py <doc>`. It lints (`tools/lint.py`), compiles
and fails on missing fonts. Fix every error; read the warnings.
## Reusable prompt
> Write the content of an AIMsight technical document in Typst for the
> AIMsight brand. Keep the `#show: technical-document.with(...)` header of
> the starter document and change only title, subtitle, document-label,
> authors, lang, density and show-toc; never set revision, date or draft.
> Use only the public helpers of TEMPLATE_GUIDE.md section 3 (headings,
> lists, tables, #fig, #screenshot, #note, #tip, #caution, #warning, #danger,
> #todo, #data-table, #fig-row, #icon). Never use place, move, grid, raw
> colours, font or page settings.
> Use `-` for bullets and `#strong[...]` for emphasis, never `*`. Use
> root paths for pictures. In math, quote multi-letter labels, group
> subscripts with parentheses, use op("...") for named operators and avoid
> LaTeX commands. Respect the text budgets. Check every delimiter before
> returning the document.
@@ -0,0 +1,569 @@
# AIMsight Typst template guide
This is the canonical authoring reference for colleagues and LLM-generated AIMsight documents.
The system has three document families:
1. brochure / concept note (`templates/brochure.typ`)
2. technical/manual/report (`templates/technical.typ`)
3. presentation (`templates/presentation.typ`)
All three share the same theme, the Inter typeface (bundled in `fonts/`), the AIMsight colour system (`docs/COLOR_SYSTEM.md`) and the company identity in `theme/company.typ`.
Common to all three families:
- `logo: auto` is the AIMsight logo, `logo: none` hides it; a root path or `image(...)` co-brands.
- `lang` selects the template wording (callout labels, revision, classification, dates, the country in the address): en, fr, de, es, it.
- In a factory build, revision, date and a DRAFT mark come from git (section 3.1); nothing to set by hand.
### Where documents live
Colleagues do not edit this repository to write a document. They start from one of the document factories on Gitea (`docfactory-technical`, `docfactory-brochure`, `docfactory-presentation`), which carry a frozen copy of this brand in `brand/`. Inside a factory, imports are project-root paths:
```typst
#import "/brand/templates/technical.typ": *
```
The examples in this repository import `../templates/...` because here the brand *is* the project root. Everything else in this guide is identical.
### Checking a document while writing
- **VS Code**: Tinymist preview (`Ctrl+K V`), configured by the factory's `.vscode/settings.json` with the brand fonts only; *Run Task* builds, watches, lints and previews.
- **Browser**: `python brand/tools/preview.py` shows every document and language at http://127.0.0.1:8770, refreshed on every save, with compile errors in the page. In the Claude Code desktop app, the factory's `.claude/launch.json` opens it in the browser pane.
- **Build**: `python brand/tools/build.py <doc>` lints, compiles and stamps; `--png` writes page images.
- **Brand changes**: `python tests/run.py` in this repository runs every check and leaves one test PDF per document type in `build/test-pdfs/`; `examples/technical-specimen.typ` shows every technical helper.
---
## 1. General authoring rules
### Content files should contain
- wording, data and asset paths;
- semantic choices such as `variant: "dark"`, `ratio: "40-60"` or plot `aspect`;
- standard Typst content: paragraphs, `-` lists, `#strong[...]`, tables, figures.
### Content files should not contain
- arbitrary `place(...)`, `move(...)`, `grid(...)` or `block(...)` layout code;
- millimetre/point nudges for page furniture;
- raw brand colours;
- manual logo paths;
- duplicated margins, font sizes or page geometry.
If a content file needs a new recurring layout, add a reusable function to the template rather than placing one-off geometry in the document.
### Asset paths
Use project-root-relative paths:
```typst
"/assets/images/site-photo.jpg"
"/assets/plots/displacement.png"
```
Compile from the repository root with `--root .`.
Why always root paths: Typst resolves a string path relative to the file that calls `image()`, which for `#fig("...")`, `hero: "..."` or `brochure-photo("...")` is the template file in `brand/templates/`, not your document. A relative string such as `"images/x.png"` therefore points into the brand and fails. Either:
- use a root path: `#fig("/documents/user-manual/images/x.png")`, or
- pass content, which is resolved where you write it: `#fig(image("images/x.png"))`.
`tools/lint.py` warns about relative string paths.
### Text budgets
The ranges below are conservative practical targets from the validated layouts. They are not parser limits. If content exceeds the recommended maximum, shorten or split the page/slide rather than shrinking typography.
---
# 2. Brochure
`examples/brochure-specimen.typ` shows the cover, the page types and every helper of this section; build it with `--input variant=light` for the light variant.
Each page function produces exactly one printed page. A cover whose rail runs past the bottom margin, or a page whose content runs onto the next page, gets a red overflow note in drafts and stops a release build: shorten the text or split it into two pages. Translations work as in the technical family (`main.<lang>.typ`, `new.py translate`).
Import:
```typst
#import "../templates/brochure.typ": *
```
Canonical setup:
```typst
#let variant = "dark"
#let edition = [CONFIDENTIAL · SHARED UNDER NDA]
#show: brochure.with(
doc-title: [Project title],
edition: edition,
variant: variant,
lang: "en",
)
```
`website` defaults to the company web address; `draft` follows the build like the technical family.
Supported variants:
- `"dark"` — preferred full-height dark right rail;
- `"light"` — same geometry with a light rail/title treatment.
Do not create separate cover layouts for these variants.
## 2.1 `brochure-cover(...)`
The only public brochure cover. It is the accepted former `brochure-cover-concept-last` layout.
Typical call:
```typst
#brochure-cover(
variant: variant,
edition: edition,
kicker: [Power-network monitoring concept],
context-lines: ([Ground], [Tower], [Conductors], [In context]),
title: [Integrated Optical Monitoring of Overhead Power Networks],
hero: "/assets/images/power-network-hero-demo.png",
intro-title: [From the ground to the conductor],
intro-body: [
First short paragraph.
Second short paragraph.
],
highlight: [One concise high-value statement.],
closing-note: [One short closing paragraph.],
sidebar: (...),
)
```
### Cover field guidance
| Field | Purpose | Recommended length |
| --- | --- | --- |
| `kicker` | small descriptor under logo | 2–6 words; ideally <= 40 characters |
| `context-lines` | stacked upper-right context | 3–4 items; each 1–3 words |
| `title` | main full-width band title | 5–12 words; ideal 45–75 characters; avoid > 90 |
| `strapline` | optional small line in title band | 3–8 words; <= 55 characters |
| `hero` | hero image path/content | one landscape image; use a meaningful wide crop |
| `intro-title` | lower-left section heading | 3–8 words; <= 55 characters |
| `intro-body` | main introductory copy | 80–150 words total; usually 2 paragraphs |
| `highlight` | red-bar emphasis statement | 12–28 words; preferably 1 sentence |
| `closing-note` | small closing paragraph | 25–55 words |
| `sidebar` | structured right-rail content | normally 2 sections, 3–4 items total |
### Sidebar schema
Use data, not layout calls:
```typst
sidebar: (
(
title: [Commercially relevant advantages],
items: (
(label: [Electronics away from power lines], detail: [Short explanation.]),
(label: [Many points measured at once], detail: [Short explanation.]),
),
),
(title: [Status], body: [Concept and pilot applications.]),
)
```
Sidebar budgets:
- section title: 1–5 words;
- item label: 2–7 words;
- item detail: 12–28 words;
- free section `body`: ideally <= 35 words.
## 2.2 `brochure-page(...)`
Standard internal page:
```typst
#brochure-page(
variant: variant,
kicker: [System range],
title: [A single station spans multiple monitoring time scales],
body: [ ... ],
sidebar: (...),
)
```
Recommended content budget:
- `kicker`: 2–6 words;
- `title`: 4–12 words, ideally <= 70 characters;
- text-only main body: roughly 180–320 words;
- with one major figure/table: roughly 80–180 words;
- sidebar: usually 60–120 words total.
Use the reusable helpers instead of custom page geometry:
- `brochure-photo(...)`
- `engineering-figure(...)`
- `engineering-svg(...)`
- `specification-table(...)`
- `metric-grid(...)`
- `comparison-panels(...)`
- `pullquote[...]`
- `accent-statement[...]`
## 2.3 `brochure-final-page(...)`
Same content grammar as `brochure-page`, plus an optional bottom-left contact block:
```typst
#brochure-final-page(
...,
contact-label: [Contact],
contact: [
AIMsight SA\
Route de Cité-Ouest 2 · 1196 Gland · Switzerland\
info\@aimsight.ch · aimsight.ch
],
)
```
Keep `contact` to roughly 2–4 short lines.
---
# 3. Technical / manual / report
`examples/technical-specimen.typ` shows every helper of this section with its result.
Import:
```typst
#import "../templates/technical.typ": *
```
Canonical setup:
```typst
#show: technical-document.with(
title: [AIMsight Optical Monitoring Station Manual],
subtitle: [Installation and operation through the local web interface],
document-label: [AIMsight Station Guide],
lang: "en",
density: "compact",
)
```
## 3.1 Main fields
| Field | Use | Guidance |
| --- | --- | --- |
| `title` | document title | 2–12 words; ideally <= 75 characters |
| `subtitle` | optional clarification | 3–15 words; <= 100 characters |
| `document-label` | running header | 2–8 words; <= 55 characters |
| `authors` | first-page author line | `[Name]`, `(name: [Name])` or an array of either; all names are shown |
| `lang` | document language | `en`, `fr`, `de`, `es`, `it`: hyphenation, callout and footer wording, dates, country in the address |
| `density` | body density | `"compact"` for manuals and FAQs; `"standard"` for reports and white papers |
| `abstract` | summary box on page 1 | 40–150 words; several paragraphs allowed |
| `venue` | client / project line | one short line |
| `document-id` | controlled-document number | e.g. `[AIM-UM-0012]`; page 1 and every footer |
| `classification` | handling class | `"public"`, `"internal"`, `"confidential"`, `"restricted"`; page 1 and every footer, in the document language |
| `approved-by` | approver of the issued revision | a name |
| `show-toc` | include contents | `true` for manuals and reports; `false` for short notes. With contents, the front matter is numbered i, ii and the body starts at 1 |
| `toc-depth` | heading levels in the contents | default 3; 1 or 2 for long reports |
| `section-numbering` | numbered headings | `true` (default) numbers headings 1, 1.1, 1.1.1 |
| `address-mode` | company address | `"end"`, `"footer"` or `"none"` |
| `logo` | header logo | `auto` (AIMsight), `none`, or a root path / `image(...)` for co-branded documents |
| `revision`, `date`, `draft` | issue metadata | leave unset in factories: the build stamps them from git (below) |
Address modes:
- `"end"` (default): the company address sits at the bottom of the last page. It stays on the page where the text ends when it fits below the text (footnotes included); otherwise it goes to the bottom of one extra page. `tests/end_address.py` checks this on 516 layouts.
- `"footer"`: one-line address in the running footer, for short notes.
- `"none"`: no address.
### Versions from git
`python brand/tools/build.py` passes `--input revision=…`, `date=…`, `draft=…` and `history=…` to Typst, so a document that leaves these fields unset always says which sources produced it:
| Build | Footer | DRAFT mark |
| --- | --- | --- |
| tag `station-manual/v1.5.0` on HEAD, clean tree | `Revision 1.5.0`, tag date | no |
| tag `rapport-planches/rev-B` on HEAD, clean tree | `Revision B`, tag date | no |
| 3 commits after the tag | `Revision 1.5.0-3-gabc1234` | yes |
| uncommitted changes | `Revision 1.5.0+local` | yes |
Per-document tags (`<doc>/v…`, `<doc>/rev-…`) win over global ones (`v…`, `rev-…`). An annotated tag can carry the real issue date (`GIT_COMMITTER_DATE=2026-10-19 git tag -a …`). `build.py --release` refuses anything that is not a clean tagged build, stops on `#todo`, `#placeholder-figure` and overflowing slides, and writes PDF/A-2b.
`#revision-history()` prints a table of every tag of the document (revision, date, tag message, author). Pass `entries:` to give the history by hand.
## 3.2 Translations
A translation is a sibling file `main.<lang>.typ` in the same folder, with the same structure and `lang` set; it shares `images/` and the git tags of the document and builds to `<doc>-<lang>.pdf`. `python brand/tools/new.py translate <doc> --lang fr` starts one; `lint.py` warns when its headings drift from `main.typ`.
## 3.3 Flow-content guidance
The technical template is flow-based, so pages may break naturally. Do not target a fixed word count per page.
Conservative content guidance (checked as warnings by `lint.py`):
- H1 heading: 2–10 words; H2/H3: 2–12 words;
- paragraph: preferably 40–120 words;
- callout: 15–90 words;
- figure caption: 5–25 words;
- table cell: preferably <= 25 words; split complex explanations out of the table;
- bullet: usually 5–25 words.
## 3.4 Helpers
Callouts; labels follow `lang`, and the safety levels escalate caution (amber) → warning (orange) → danger (red):
```typst
#note[...] #tip[...] #caution[...] #warning[...] #danger[...]
```
Pictures (`alt:` is the text read by screen readers):
```typst
#fig("/documents/my-doc/images/kit.jpg", width: 80%, caption: [Kit contents.], alt: "Open transport case")
#fig(image("plot.png"), caption: [A file next to the document, passed as content.])
#fig-row("/documents/my-doc/images/a.png", "/documents/my-doc/images/b.png", caption: [Two to four pictures, one caption.])
#screenshot("/captures/explore-overview.png", caption: [UI capture with a hairline frame.])
Press the record button #icon("/documents/my-doc/images/record.svg", alt: "record") to start.
```
Tables:
```typst
#data-table(
columns: (1.2fr, 0.6fr, 2fr),
header: ([Signal], [Unit], [Purpose]),
zebra: true, // optional stripes for long tables
[Relative H / V], [mm], [Displacement relative to the reference.],
)
```
A plain `#table` is styled too; put its header row in `table.header(...)` so it repeats after page breaks.
Reports and drafting:
```typst
#summary-card([01], [Transverse view], meta: [Upstream abutment])[Joint, bearing and rail movements.]
#revision-history()
#todo[serial number of station 2]
#placeholder-figure([Station 2 installed on the abutment.], note: [Photo to take on site])
```
`#todo` and `#placeholder-figure` render as amber markers in drafts and stop a release build.
Use standard Typst headings, lists, quotes, code blocks, maths, footnotes and `@label` references in the body. Avoid manual page positioning.
---
# 4. Presentation
Import:
```typst
#import "../templates/presentation.typ": *
```
Setup:
```typst
#show: presentation.with(
title: [AIMsight presentation],
author: [AIMsight SA],
)
```
Supported visual variants:
- `"light"` — white background;
- `"steel"` — AIMsight teal, used for title/closing slides;
- `"deep"` — darker `#10232D`, used for section/quote contrast slides.
The section slide defaults to `deep`, so slide 2 is intentionally darker than the title slide. On `steel` and `deep` slides the logo switches to its white-wordmark version.
Slide content taller than the slide gets a dashed red frame and an "Overflow" note in drafts and stops a release build: split the slide.
## 4.1 Slide selection and text budgets
### `title-slide(...)`
Use for the opening slide.
- `kicker`: 2–6 words;
- `title`: 4–10 words, ideal <= 55 characters, avoid > 75;
- `subtitle`: 6–18 words, <= 110 characters;
- `hero`: one image path.
### `section-slide(...)`
Use for a chapter/section divider.
- `index`: short, e.g. `01`;
- `title`: 2–8 words, <= 55 characters;
- `subtitle`: 5–16 words, <= 100 characters.
### `statement-slide(...)`
Use for one strong claim with short support.
- `title`: 4–10 words;
- `statement`: 8–22 words;
- `support`: 8–30 words;
- `eyebrow`: 1–4 words.
### `content-slide(...)`
Use for concise text or bullets.
- `title`: 4–11 words;
- body: normally 3–5 bullets;
- each bullet: 5–16 words;
- total body: roughly 25–70 words.
If the body approaches paragraph length, split the slide.
### `two-column-slide(...)`
Use for text + visual or two balanced content groups.
Allowed ratios: `"40-60"`, `"50-50"`, `"60-40"`.
- `title`: 4–11 words;
- text column: roughly 25–60 words or 3–5 bullets;
- visual column: one primary diagram/image is preferred.
### `image-slide(...)`
Use when the image carries the message.
- `title`: 4–12 words;
- `caption`: 5–25 words;
- `fit`: normally `"cover"`; use `"contain"` only when cropping would remove information.
### `gallery-slide(...)`
Use for 2–3 photographs/application views.
- slide title: 4–10 words;
- figure title: 1–5 words;
- caption: 3–14 words.
Use `plot-gallery-slide` instead for charts/plots.
### `plot-gallery-slide(...)`
Use for Matplotlib/scientific figures. Plots use `fit: "contain"` and are never cropped.
Each plot item may contain:
```typst
(
image: "/assets/plots/example.png",
aspect: 1.4,
title: [Figure title],
legend: [Short interpretation or compact bullets.],
)
```
Guidance:
- plot title: 2–8 words;
- legend: 1 short paragraph or 1–3 bullets, about 8–40 words total;
- 1 portrait/near-square plot: automatic figure-left / explanation-right layout;
- 1 wide plot: full-width;
- 2 plots: side by side;
- 3 compact plots: one row when labels remain readable; otherwise grid/split;
- 4 plots: overview only; use 2×2.
The `aspect` value is figure metadata (`width / height`), not a page-layout nudge.
### `metric-slide(...)`
Use for 2–4 headline values.
- metric value: ideally <= 10 characters;
- metric label: 2–8 words;
- optional `lead`: <= 25 words.
### `comparison-slide(...)`
Use for A/B or two-mode comparisons.
- main title: 4–10 words;
- left/right panel title: 1–4 words;
- each panel: 3–5 bullets, each 4–12 words.
### `architecture-slide(...)`
Use for 3–4 sequential/system stages.
- slide title: 4–10 words;
- stage title: 1–3 words;
- stage detail: 4–14 words;
- optional note: <= 20 words.
### `timeline-slide(...)`
Use for 3–5 process steps.
- step title: 1–3 words;
- step detail: 3–10 words.
### `case-study-slide(...)`
Use for one project image + result + facts.
- title: 4–11 words;
- project eyebrow: 1–5 words;
- result: 5–15 words;
- facts: normally 3 items;
- fact label: 1–3 words;
- fact value: 1–8 words.
### `quote-slide(...)`
Use sparingly for a testimonial or concise principle.
- quote: 12–45 words;
- attribution: 2–10 words;
- note: <= 20 words.
### Overflow and translations
Every slide function produces exactly one slide. Content taller than the slide gets a dashed red frame and an overflow note in drafts and stops a release build. Translations are `main.<lang>.typ` next to the deck, created with `new.py translate`; the draft marker and the closing-slide address follow `lang`.
An accent metric (`accent: true`) uses AIMsight red on light slides and a lighter red (`aim-red-on-dark`) on steel and deep slides, where the brand red would be unreadable.
### `closing-slide(...)`
`contact` and `address` default to the company web/e-mail line and postal address.
- title: 3–10 words;
- subtitle: 5–16 words;
- contact: one short line;
- address: 1–3 short lines.
---
# 5. LLM authoring contract
When generating AIMsight Typst content:
1. Read this guide and the canonical example for the target family before writing.
2. Use only public functions documented here; do not invent parameters or helpers.
3. Use named parameters for page/slide-level calls.
4. Keep layout decisions in the template. Do not generate `place`, `move`, `grid`, custom page margins, brand colours or point/mm offsets in content documents.
5. Use `-` for lists and `#strong[...]` for emphasis.
6. Use project-root asset paths (`/assets/...`).
7. Keep to the conservative field-length budgets above.
8. If content does not fit a presentation slide, shorten or split it. Do not shrink typography.
9. Use AIMsight red only for monitored points, alarms/exceptions or rare high-priority cues.
10. Compile with `python brand/tools/build.py` (lint, budgets, compile) and inspect the rendered pages (`--png` or `preview.py`) before delivery.
11. Follow the syntax rules in `docs/LLM_AUTHORING.md` (math, tables, escaping).
12. Mark facts you could not verify with `#todo[...]`; never invent values, dates or revisions.
For presentations, the preferred decision sequence is: choose the narrative unit → choose the dedicated slide function → fill only its semantic fields → compile → split if necessary.
For brochures, prefer the single canonical cover and standard page grammar instead of inventing new page layouts.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+95
View File
@@ -0,0 +1,95 @@
Inter 4.001 (static TTF faces used by the AIMsight brand)
Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
The Italic and Medium Italic faces were extracted unchanged from Inter.ttc.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+13
View File
@@ -0,0 +1,13 @@
// AIMsight Typst brand — single entry point.
//
// Documents normally import one family directly:
// #import "/brand/templates/technical.typ": *
// #import "/brand/templates/brochure.typ": *
// #import "/brand/templates/presentation.typ": *
// This file re-exports all three plus the theme, e.g. for a future
// `@aimsight/brand` package.
#import "theme/index.typ": *
#import "templates/technical.typ": *
#import "templates/brochure.typ": *
#import "templates/presentation.typ": *
#let brand-version = version(1, 1, 0)
@@ -0,0 +1,75 @@
// Brochure / concept note. Field budgets: brand/docs/TEMPLATE_GUIDE.md section 2.
// Hero and photos: root paths such as "/documents/{{slug}}/images/hero.jpg".
#import "/brand/templates/brochure.typ": *
#let variant = "dark"
#let edition = [CONFIDENTIAL · SHARED UNDER NDA]
#show: brochure.with(
doc-title: [{{title}}],
edition: edition,
variant: variant,
lang: "{{lang}}",
)
#brochure-cover(
variant: variant,
edition: edition,
kicker: [Short descriptor, 2-6 words],
context-lines: ([Context one], [Context two], [Context three]),
title: [{{title}}],
hero: none, // "/documents/{{slug}}/images/hero.jpg"
intro-title: [Section heading, 3-8 words],
intro-body: [
First introductory paragraph. Together with the second one, aim for 80-150 words: what the reader's problem is and why it matters.
Second paragraph: what AIMsight brings, stated in terms of the reader's outcome rather than features.
],
highlight: [One high-value statement of 12-28 words, the sentence you want remembered.],
closing-note: [A short closing paragraph of 25-55 words that says what this document is for.],
sidebar: (
(
title: [Key advantages],
items: (
(label: [Advantage one], detail: [One sentence of 12-28 words explaining the advantage.]),
(label: [Advantage two], detail: [One sentence of 12-28 words explaining the advantage.]),
),
),
(title: [Status], body: [One line on availability or maturity.]),
),
)
#brochure-page(
variant: variant,
kicker: [Section kicker],
title: [A page title of 4-12 words],
body: [
Body text of 80-180 words when the page carries a figure or metrics.
#metric-grid((
(value: [0.4 mm], label: [what the value means]),
(value: [200 Hz], label: [what the value means]),
))
],
sidebar: (
(
title: [Sidebar title],
items: (
(label: [Label], detail: [Short explanation.]),
),
),
),
)
#brochure-final-page(
variant: variant,
kicker: [Next step],
title: [A closing page title of 4-12 words],
body: [
== Sub-heading
Closing body text: what the reader should do next.
],
contact-label: [Contact],
contact: company-address(style: "postal"),
)
@@ -0,0 +1,46 @@
// 16:9 presentation. One slide function = one slide; budgets in
// brand/docs/TEMPLATE_GUIDE.md section 4. Split slides rather than shrink text.
#import "/brand/templates/presentation.typ": *
#show: presentation.with(
title: [{{title}}],
author: [AIMsight SA],
lang: "{{lang}}",
)
#title-slide(
kicker: [Short kicker],
title: [{{title}}],
subtitle: [One sentence of 6-18 words that frames the talk],
hero: none, // "/documents/{{slug}}/images/hero.jpg"
)
#section-slide(
index: [01],
title: [First section],
subtitle: [What this section establishes],
)
#content-slide(
title: [A slide title states the message],
body: [
- Three to five bullets
- Each 5-16 words
- The title carries the conclusion
],
)
#metric-slide(
title: [Numbers worth remembering],
metrics: (
(value: [0.4 mm], label: [what it means]),
(value: [200 Hz], label: [what it means]),
(value: [Edge], label: [what it means], accent: true),
),
)
// Contact and address default to the company block (theme/company.typ).
#closing-slide(
title: [Let's monitor what matters.],
subtitle: [Camera-based asset monitoring],
)
@@ -0,0 +1,22 @@
// Short technical or application note: no contents page, one-line address
// in the footer. Revision, date and DRAFT come from git.
#import "/brand/templates/technical.typ": *
#show: technical-document.with(
title: [{{title}}],
document-label: [{{label}}],
lang: "{{lang}}",
density: "compact",
show-toc: false,
address-mode: "footer",
)
= Context
#todo[Why this note exists, in two or three sentences.]
= Content
#todo[Body. Keep paragraphs to 40-120 words.]
#note[#todo[The one thing the reader must remember.]]
@@ -0,0 +1,44 @@
// Technical or installation report. Revision, date and DRAFT come from git.
#import "/brand/templates/technical.typ": *
#show: technical-document.with(
title: [{{title}}],
subtitle: [#todo[Site — monitoring objective]],
document-label: [{{label}}],
authors: ([#todo[Author] — AIMsight SA],),
venue: [#todo[Client — project]],
lang: "{{lang}}",
density: "standard",
justify-text: true,
abstract: [#todo[Three to five sentences: what was measured, why, and the main conclusion.]],
)
= Executive summary
#todo[One paragraph per key finding.]
= Measurement concept
#summary-card([01], [#todo[System name]], meta: [#todo[Location]])[#todo[Role of the system]]
#summary-card([02], [#todo[System name]], meta: [#todo[Location]])[#todo[Role of the system]]
#placeholder-figure([#todo[Overview of the installation.]], note: [Site photo or plan])
= Installation
#table(
columns: (1fr, 1.4fr),
table.header([#strong[Item]], [#strong[Value]]),
[Installation date], [#todo()],
[Systems], [#todo()],
[Acquisition], [#todo()],
)
= Results
#todo[Plots, each with `#fig("/documents/{{slug}}/images/<plot>.png", caption: [...])`, and their interpretation.]
= Conclusion
#todo[Conclusion and recommended next steps.]
@@ -0,0 +1,65 @@
// Software user manual. Pictures: /documents/{{slug}}/images/...;
// UI captures: /captures/<name>.png from captures.toml (python brand/tools/capture.py).
// Revision, date and DRAFT come from git: do not set them here.
#import "/brand/templates/technical.typ": *
#show: technical-document.with(
title: [{{title}}],
subtitle: [User manual],
document-label: [{{label}}],
lang: "{{lang}}",
density: "compact",
)
= About this manual
This manual describes #todo[product and version]. It is written for #todo[audience: operators, installers, administrators].
#note[Screens may differ slightly from your installation. The captures in this manual are regenerated for every release.]
= Getting started
== Requirements
- #todo[browser, network access, credentials]
- #todo[hardware or licence prerequisites]
== Signing in
1. Open #todo[address] in a supported browser.
2. Enter your user name and password.
3. #todo[first screen the user sees]
#placeholder-figure([Start page after signing in.], note: [Add a capture to captures.toml, run capture.py, then replace this block with `#screenshot("/captures/<name>.png", caption: [...])`])
= Everyday tasks
== #todo[Task name]
Describe the goal of the task in one or two sentences.
1. #todo[step]
2. #todo[step]
3. #todo[step]
#tip[One practical shortcut or good practice for this task.]
= Reference
== Settings
#table(
columns: (1.2fr, 0.8fr, 2fr),
table.header([#strong[Setting]], [#strong[Default]], [#strong[Effect]]),
[#todo()], [#todo()], [#todo()],
)
= Troubleshooting
#table(
columns: (1.4fr, 2fr),
table.header([#strong[Symptom]], [#strong[What to do]]),
[#todo()], [#todo()],
)
#caution[Contact AIMsight support before changing settings that are not described in this manual.]
@@ -0,0 +1,717 @@
// ============================================================================
// AIMsight brochure template
// Canonical A4 editorial system. One cover grammar, one content-page grammar.
// Layout tuning lives in theme/geometry.typ, not in content documents.
// ============================================================================
#import "../theme/index.typ": *
#let sidebar-width = brochure-sidebar-width
#let sidebar-band-width = brochure-sidebar-band-width
#let column-gutter = brochure-column-gutter
#let margin-left = brochure-margin-left
#let margin-right = brochure-margin-right
#let content-width = brochure-page-width - margin-left - margin-right
#let main-column-width = content-width - sidebar-width - column-gutter
#let _is-dark(variant) = {
if variant == "dark" { true }
else if variant == "light" { false }
else { panic("Unknown brochure variant: " + variant + ". Use dark or light.") }
}
#let _side-fill(variant) = if _is-dark(variant) { brochure-side-dark } else { brochure-side-light }
#let _side-ink(variant) = if _is-dark(variant) { white } else { ink }
#let _side-quiet(variant) = if _is-dark(variant) { brochure-side-dark-soft } else { quiet }
#let _side-rule(variant) = if _is-dark(variant) { brochure-side-dark-rule } else { rule }
#let _side-title(variant) = if _is-dark(variant) { white } else { steel }
#let _side-accent(variant) = if _is-dark(variant) { brochure-side-dark-soft } else { data-steel }
#let _cover-band-fill(variant) = if _is-dark(variant) { steel } else { brochure-cover-light-band }
#let _cover-title-fill(variant) = if _is-dark(variant) { white } else { deep-steel }
#let _cover-frame-color(variant) = if _is-dark(variant) { brochure-side-dark-rule } else { brochure-cover-light-rule }
// -----------------------------------------------------------------------------
// Identity and small editorial helpers
// -----------------------------------------------------------------------------
// logo: auto = AIMsight logo, none = no logo, or a root path / bytes / content
// (same meaning as in the technical and presentation templates).
#let _render-logo(logo: auto, height: 9.5mm) = resolve-logo(logo, height: height)
#let _draft-mark(draft) = {
let value = if draft == auto { sys.inputs.at("draft", default: "false") } else { draft }
if value == true or value == "true" {
context place(center + horizon, rotate(-40deg, text(size: 96pt, weight: "bold", fill: rule.transparentize(55%), term("draft"))))
}
}
// -----------------------------------------------------------------------------
// One page per page function
// A brochure page is designed as exactly one printed page. Content that runs
// onto the next page (or a sidebar that runs past the bottom margin) is a
// layout defect: it leaves a <aimsight-overflow> marker (tests), a red note in
// drafts and stops a release build (build.py --release). Shorten or split.
// -----------------------------------------------------------------------------
#let _is-release() = sys.inputs.at("release", default: "false") == "true"
#let _page-counter = counter("aimsight-brochure-page")
#let _overflow(what, detail) = {
if _is-release() { panic("Brochure " + what + " overflows (" + detail + "): shorten it or split it into two pages.") }
[#metadata((family: "brochure", what: what, detail: detail)) <aimsight-overflow>]
block(
width: 100%,
inset: (x: 6pt, y: 4pt),
stroke: (paint: aim-red, thickness: 1pt, dash: "dashed"),
text(size: 8pt, weight: "semibold", fill: aim-red)[Overflow: this #what #detail. Shorten it or split it into two pages.],
)
}
#let _page-start() = {
_page-counter.step()
context [#metadata(_page-counter.get().first()) <aimsight-brochure-start>]
}
#let _page-end(what) = context {
let id = _page-counter.get().first()
let starts = query(<aimsight-brochure-start>).filter(m => m.value == id)
if starts.len() > 0 {
let first = starts.first().location().page()
if here().page() > first {
_overflow(what, "runs from page " + str(first) + " to page " + str(here().page()))
}
}
}
#let _eyebrow(body, fill: data-steel) = text(
size: 7.8pt,
weight: "semibold",
tracking: 0.08em,
fill: fill,
upper(body),
)
#let _page-background(variant) = place(
right + top,
rect(width: sidebar-band-width, height: 100%, fill: _side-fill(variant)),
)
#let _running-header(logo, edition, variant) = context {
let p = counter(page).at(here()).first()
if p > 1 {
v(8mm)
grid(
columns: (1fr, sidebar-width),
column-gutter: column-gutter,
align: (left + horizon, right + horizon),
_render-logo(logo: logo, height: 9.2mm),
if edition == none { [] } else {
text(size: 7.6pt, weight: "medium", fill: _side-accent(variant), edition)
},
)
}
}
#let _running-footer(website, variant) = context {
grid(
columns: (1fr, sidebar-width),
column-gutter: column-gutter,
align: (left + horizon, right + horizon),
text(size: 7.3pt, fill: quiet, website),
text(size: 7.3pt, fill: _side-quiet(variant), counter(page).display("1")),
)
}
// -----------------------------------------------------------------------------
// Public reusable content components
// -----------------------------------------------------------------------------
#let pullquote(body, mark: none) = block(
width: 100%,
above: 11pt,
below: 13pt,
[
#line(length: 100%, stroke: 0.75pt + data-steel)
#v(7pt)
#if mark == none {
text(size: 11.5pt, weight: "medium", fill: steel, body)
} else {
grid(
columns: (auto, 1fr),
column-gutter: 9pt,
align: top,
if type(mark) == str { image(mark, height: 4.2mm) } else { box(height: 4.2mm, mark) },
text(size: 11.5pt, weight: "medium", fill: steel, body),
)
}
#v(7pt)
#line(length: 34%, stroke: 0.45pt + rule)
],
)
#let accent-statement(body) = block(
width: 100%,
above: 10pt,
below: 12pt,
[
#grid(
columns: (2.2pt, 1fr),
column-gutter: 9pt,
align: top,
rect(width: 2.2pt, height: 16mm, fill: aim-red),
text(size: 11.5pt, weight: "semibold", fill: steel, body),
)
],
)
#let brochure-visual(body, caption: none) = block(
width: 100%,
above: 10pt,
below: 12pt,
[
#block(width: 100%, radius: radius-small, clip: true, body)
#if caption != none {
v(4pt)
text(size: brochure-caption-size, fill: quiet, caption)
}
],
)
#let brochure-photo(path, caption: none, height: 64mm, fit: "cover") = brochure-visual(
image(path, width: 100%, height: height, fit: fit),
caption: caption,
)
#let engineering-figure(body, label: none, note: none, meta: none, caption: none) = block(
width: 100%,
above: 11pt,
below: 13pt,
[
#if label != none {
_eyebrow(label, fill: steel)
v(4pt)
line(length: 100%, stroke: 0.45pt + rule)
v(7pt)
}
#block(width: 100%, body)
#if note != none or meta != none {
v(6pt)
grid(
columns: (1fr, auto),
column-gutter: 10pt,
if note == none { [] } else { text(size: 7.6pt, fill: quiet, note) },
if meta == none { [] } else { text(size: 7.4pt, weight: "medium", fill: data-steel, meta) },
)
}
#if caption != none {
v(4pt)
text(size: brochure-caption-size, fill: quiet, caption)
}
],
)
#let engineering-svg(path, label: none, note: none, meta: none, caption: none, width: 100%) = engineering-figure(
box(width: width, image(path, width: 100%)),
label: label,
note: note,
meta: meta,
caption: caption,
)
#let specification-table(
rows,
headers: ([Parameter], [Specification]),
columns: (0.9fr, 1.4fr),
) = block(
width: 100%,
above: 10pt,
below: 12pt,
[
#table(
columns: columns,
inset: (x: 6pt, y: 4.8pt),
stroke: 0.45pt + rule,
table.header(
table.cell(fill: cloud)[#text(size: 7.8pt, weight: "semibold", fill: steel)[#headers.at(0)]],
table.cell(fill: cloud)[#text(size: 7.8pt, weight: "semibold", fill: steel)[#headers.at(1)]],
),
..rows.flatten(),
)
],
)
#let metric-grid(metrics) = grid(
columns: (1fr, 1fr),
column-gutter: 7pt,
row-gutter: 7pt,
..metrics.map(metric => block(
width: 100%,
inset: (x: 8pt, y: 8pt),
radius: radius-small,
stroke: rule-thin + rule,
fill: cloud,
[
#text(size: 17pt, weight: "semibold", fill: if metric.at("accent", default: false) { aim-red } else { steel })[#metric.value]
#v(2pt)
#text(size: 8.4pt, fill: quiet)[#metric.label]
],
)),
)
#let comparison-panels(
left-title: [Option A],
left: [],
right-title: [Option B],
right: [],
) = {
let panel(title, content) = block(
width: 100%,
inset: (x: 9pt, y: 9pt),
radius: radius-small,
stroke: rule-thin + rule,
[
#_eyebrow(title, fill: steel)
#v(6pt)
#content
],
)
grid(
columns: (1fr, 1fr),
column-gutter: 8pt,
panel(left-title, left),
panel(right-title, right),
)
}
// -----------------------------------------------------------------------------
// Structured sidebar data
// A sidebar is a tuple of dictionaries. Each section accepts:
// title: required content
// items: optional tuple of (label:, detail:) dictionaries
// body: optional free content after the items
// -----------------------------------------------------------------------------
#let _side-section(title, body, variant) = block(
width: 100%,
above: 2pt,
below: 15pt,
[
#align(left)[
#text(size: 8.1pt, weight: "semibold", tracking: 0.065em, fill: _side-title(variant))[#upper(title)]
#v(5pt)
#line(length: 100%, stroke: 0.5pt + _side-rule(variant))
#v(8pt)
#body
]
],
)
#let _side-item(label, detail, variant) = block(
width: 100%,
below: 10pt,
[
#align(left)[
#text(size: 8.9pt, weight: "semibold", fill: _side-ink(variant))[#label]\
#v(1.5pt)
#text(size: 8.25pt, fill: _side-quiet(variant))[#detail]
]
],
)
#let _render-sidebar(sections, variant) = {
for section in sections {
let section-title = section.at("title", default: none)
let section-items = section.at("items", default: ())
let section-body = section.at("body", default: none)
if section-title != none {
_side-section(section-title, [
#for item in section-items {
_side-item(
item.at("label", default: []),
item.at("detail", default: []),
variant,
)
}
#if section-body != none { section-body }
], variant)
}
}
}
#let _contact-block(body, label: none) = block(
width: 100%,
[
#if label != none {
_eyebrow(label, fill: steel)
v(4pt)
}
#set text(size: 8pt, fill: quiet)
#set par(leading: 0.52em, spacing: 0.18em, justify: false)
#body
],
)
#let _subject-title(title, kicker: none) = block(
width: 100%,
[
#if kicker != none {
_eyebrow(kicker)
v(7pt)
}
#text(size: 17pt, weight: "semibold", fill: ink, title)
],
)
// -----------------------------------------------------------------------------
// Document setup
// -----------------------------------------------------------------------------
#let brochure(
doc-title: [AIMsight brochure],
logo: auto,
edition: none,
website: auto,
variant: "dark",
draft: auto,
lang: "en",
region: "CH",
font: font-primary,
body,
) = {
let website = if website == auto { company.web } else { website }
let _validated = _is-dark(variant)
set document(title: doc-title)
set page(
width: brochure-page-width,
height: brochure-page-height,
margin: (
left: brochure-margin-left,
right: brochure-margin-right,
top: brochure-margin-top,
bottom: brochure-margin-bottom,
),
background: [#_page-background(variant) #_draft-mark(draft)],
header: _running-header(logo, edition, variant),
footer: _running-footer(website, variant),
footer-descent: 25%,
)
set text(font: font, size: brochure-body-size, fill: ink, alternates: false, lang: lang, region: region)
set par(first-line-indent: 0em, leading: 0.62em, spacing: 0.78em, justify: false)
set list(spacing: 0.60em, indent: 1.18em, body-indent: 0.52em)
set enum(number-align: start, spacing: 0.60em, indent: 1.18em, body-indent: 0.52em)
show heading: set text(hyphenate: false)
show heading.where(level: 1): set text(size: brochure-h1-size, weight: "semibold", fill: ink)
show heading.where(level: 1): set block(above: 15pt, below: 11pt)
show heading.where(level: 2): set text(size: brochure-h2-size, weight: "semibold", fill: steel)
show heading.where(level: 2): set block(above: 14pt, below: 11pt)
show heading.where(level: 3): set text(size: brochure-h3-size, weight: "semibold", fill: ink)
show heading.where(level: 3): set block(above: 11pt, below: 7pt)
show strong: set text(weight: "semibold")
show link: underline
show link: set text(fill: steel)
show table.cell: set text(size: 8.3pt)
show table.cell: set par(leading: 0.52em, spacing: 0.22em, justify: false)
body
}
// -----------------------------------------------------------------------------
// Canonical cover — the accepted former "concept-last" layout.
// Dark and light variants share identical geometry.
// -----------------------------------------------------------------------------
#let _cover-header(
logo: auto,
edition: none,
kicker: none,
context-lines: (),
variant: "dark",
) = {
let rail-dx = brochure-cover-rail-content-dx
let rail-width = sidebar-width - rail-dx
grid(
columns: (1fr, sidebar-width),
column-gutter: column-gutter,
align: (left + top, left + top),
[
#move(dy: -7mm)[#_render-logo(logo: logo, height: 13mm)]
#if kicker != none {
v(-2mm)
_eyebrow(kicker)
}
],
[
#move(dx: rail-dx, dy: brochure-cover-rail-top-dy)[
#box(width: rail-width)[
#if edition != none {
align(left, text(
size: 7.8pt,
weight: "medium",
tracking: 0.02em,
fill: _side-accent(variant),
edition,
))
}
#if context-lines.len() > 0 {
let context-content = context-lines.map(line => upper(line)).join(linebreak())
v(brochure-cover-rail-edition-rule-gap)
line(length: 100%, stroke: brochure-cover-rail-rule-thickness + _side-rule(variant))
v(brochure-cover-rail-rule-context-gap)
move(dy: brochure-cover-rail-context-dy)[
#set par(leading: 0.58em, spacing: 0.10em, justify: false)
#text(size: 7.3pt, weight: "semibold", tracking: 0.075em, fill: _side-quiet(variant), context-content)
]
}
]
]
],
)
}
#let _cover-stack(
title,
strapline: none,
hero: none,
hero-fit: "cover",
variant: "dark",
) = {
let title-height = brochure-cover-title-band-height
let hero-height = brochure-cover-hero-height
let hero-y = title-height + brochure-cover-band-to-hero-dy
let total-height = title-height + hero-height
let separator-color = if _is-dark(variant) { white } else { brochure-cover-light-rule }
move(dx: -margin-left)[
#block(width: brochure-page-width, height: total-height)[
#place(left + top)[
#rect(width: brochure-page-width, height: title-height, fill: _cover-band-fill(variant))
]
#place(left + top, dy: hero-y)[
#box(width: brochure-page-width, height: hero-height, clip: true)[
#if hero == none {
rect(
width: brochure-page-width,
height: hero-height,
fill: cloud,
inset: 12pt,
align(center + horizon, text(size: 9pt, weight: "semibold", fill: steel)[HERO IMAGE]),
)
} else if type(hero) == str {
image(hero, width: 100%, height: hero-height, fit: hero-fit)
} else {
box(width: 100%, height: hero-height, clip: true)[#hero]
}
]
]
#place(left + top, dx: margin-left, dy: brochure-cover-title-text-dy)[
#box(width: brochure-page-width - margin-left - margin-right, height: title-height)[
#align(left + horizon)[
#set text(hyphenate: false)
#text(
size: brochure-cover-title-size,
weight: brochure-cover-title-weight,
fill: _cover-title-fill(variant),
title,
)
]
]
]
#if strapline != none {
place(
right + top,
dx: -margin-right,
dy: title-height - 7.3mm + brochure-cover-strapline-dy,
)[
#text(
size: 7.5pt,
weight: "semibold",
tracking: 0.095em,
fill: if _is-dark(variant) { brochure-side-dark-soft } else { steel },
upper(strapline),
)
]
}
// Framing overlays: zero layout height.
#place(left + top, dy: brochure-cover-top-frame-dy)[
#line(length: 100%, stroke: brochure-cover-frame-thickness + _cover-frame-color(variant))
]
#place(left + top, dx: margin-left, dy: brochure-cover-top-frame-dy)[
#line(length: 42mm, stroke: brochure-cover-accent-thickness + aim-red)
]
#place(left + top, dy: title-height + brochure-cover-band-separator-dy)[
#line(length: 100%, stroke: brochure-cover-separator-thickness + separator-color)
]
#place(left + top, dy: hero-y + brochure-cover-hero-separator-dy)[
#line(length: 100%, stroke: brochure-cover-separator-thickness + separator-color)
]
#place(left + top, dy: hero-y + hero-height + brochure-cover-hero-bottom-frame-dy)[
#line(length: 100%, stroke: brochure-cover-separator-thickness + _cover-frame-color(variant))
]
]
]
}
#let _cover-sidebar(variant, sidebar) = box(width: sidebar-width)[
#align(left)[
#set text(size: 8.7pt, fill: _side-ink(variant))
#set par(leading: 0.60em, spacing: 0.64em, justify: false)
#move(dx: brochure-sidebar-content-dx)[
#_render-sidebar(sidebar, variant)
]
]
]
#let _cover-lower(variant, body, sidebar) = {
// Zero-height anchor (not a tag, which would travel with the next element)
// marking where the lower part starts, to check the placed sidebar fits.
[#block(height: 0pt, above: 0pt, below: 0pt, width: 100%) <aimsight-cover-lower>]
block(width: 100%, breakable: true)[
#if sidebar.len() > 0 {
place(right + top, _cover-sidebar(variant, sidebar))
}
#block(width: main-column-width, breakable: true)[#body]
]
if sidebar.len() > 0 {
context {
let top = locate(<aimsight-cover-lower>).position().y
let room = brochure-page-height - brochure-margin-bottom - top
let needed = measure(_cover-sidebar(variant, sidebar)).height
if needed > room + 1pt {
_overflow("cover", "sidebar runs " + str(calc.round((needed - room) / 1mm, digits: 1)) + " mm past the bottom margin")
}
}
}
}
#let brochure-cover(
title: [Brochure title],
kicker: none,
strapline: none,
context-lines: (),
hero: none,
hero-fit: "cover",
variant: "dark",
logo: auto,
edition: none,
intro-title: none,
intro-body: [],
highlight: none,
closing-note: none,
sidebar: (),
do-pagebreak: true,
) = {
let _validated = _is-dark(variant)
_page-start()
grid(
columns: (1fr,),
row-gutter: 0pt,
_cover-header(
logo: logo,
edition: edition,
kicker: kicker,
context-lines: context-lines,
variant: variant,
),
move(dy: brochure-cover-header-to-band-dy)[
#_cover-stack(
title,
strapline: strapline,
hero: hero,
hero-fit: hero-fit,
variant: variant,
)
],
)
v(brochure-cover-hero-to-body-gap)
let lower-body = [
#if intro-title != none {
text(size: brochure-h2-size, weight: "semibold", fill: steel, intro-title)
v(8pt)
}
#intro-body
#if highlight != none { accent-statement(highlight) }
#if closing-note != none { closing-note }
]
_cover-lower(variant, lower-body, sidebar)
_page-end("cover")
if do-pagebreak { pagebreak() }
}
// -----------------------------------------------------------------------------
// Standard content page / final content page
// -----------------------------------------------------------------------------
#let _brochure-page(
title: [Application],
kicker: none,
body: [],
sidebar: (),
variant: "dark",
bottom-reserve: 0mm,
do-pagebreak: true,
) = {
let _validated = _is-dark(variant)
_page-start()
grid(
columns: (1fr, sidebar-width),
column-gutter: column-gutter,
row-gutter: 8mm,
_subject-title(title, kicker: kicker),
none,
[
#body
#if bottom-reserve > 0mm { v(bottom-reserve) }
],
if sidebar.len() == 0 { none } else {
[
#align(left)[
#set text(size: 8.7pt, fill: _side-ink(variant))
#set par(leading: 0.60em, spacing: 0.64em, justify: false)
#move(dx: brochure-sidebar-content-dx)[#_render-sidebar(sidebar, variant)]
]
]
},
)
_page-end("page")
if do-pagebreak { pagebreak() }
}
#let brochure-page(
title: [Application],
kicker: none,
body: [],
sidebar: (),
variant: "dark",
) = _brochure-page(
title: title,
kicker: kicker,
body: body,
sidebar: sidebar,
variant: variant,
bottom-reserve: 0mm,
do-pagebreak: true,
)
#let brochure-final-page(
title: [Application],
kicker: none,
body: [],
sidebar: (),
variant: "dark",
contact: none,
contact-label: none,
) = {
if contact != none {
place(
left + bottom,
dy: brochure-final-contact-dy,
box(width: main-column-width)[#_contact-block(contact, label: contact-label)],
)
}
_brochure-page(
title: title,
kicker: kicker,
body: body,
sidebar: sidebar,
variant: variant,
bottom-reserve: if contact == none { 0mm } else { brochure-final-contact-reserve },
do-pagebreak: false,
)
}
@@ -0,0 +1,745 @@
// ============================================================================
// AIMsight presentation template
// Explicit 16:9 slide API. One slide function = one deterministic slide.
// Geometry and colour decisions live in theme/.
// ============================================================================
#import "../theme/index.typ": *
#let _slide-inner-width = slide-width - 2 * slide-margin-x
#let _slide-inner-height = slide-height - slide-margin-top - slide-margin-bottom
#let _variant-colors(variant) = {
if variant == "light" {
(background: white, foreground: ink, secondary: data-steel, rule-color: rule, dark: false)
} else if variant == "steel" {
(background: steel, foreground: white, secondary: brochure-side-dark-soft, rule-color: brochure-side-dark-rule, dark: true)
} else if variant == "deep" {
(background: slide-deep, foreground: white, secondary: brochure-side-dark-soft, rule-color: brochure-side-dark-rule, dark: true)
} else {
panic("Unknown slide variant: " + variant + ". Use light, steel or deep.")
}
}
#let _visual(value, width: 100%, height: auto, fit: "cover") = {
if value == none { [] }
else if type(value) == str or type(value) == bytes { image(value, width: width, height: height, fit: fit) }
else { box(width: width, height: height, clip: true, value) }
}
#let _ratio-columns(ratio) = {
if ratio == "40-60" { (2fr, 3fr) }
else if ratio == "50-50" { (1fr, 1fr) }
else if ratio == "60-40" { (3fr, 2fr) }
else { panic("Unknown column ratio: " + ratio + ". Use 40-60, 50-50 or 60-40.") }
}
#let _slide-number(fill) = context {
text(size: slide-footer-size, fill: fill, counter(page).display("1"))
}
#let _slide-footer(
source: none,
footer-note: none,
variant: "light",
show-logo: true,
) = {
let colors = _variant-colors(variant)
let meta = grid(
columns: (1fr, auto),
column-gutter: 10pt,
align: (left + horizon, right + horizon),
if source == none { [] } else {
text(size: slide-footer-size, fill: colors.secondary, source)
},
if footer-note == none { [] } else {
text(size: 9pt, weight: "medium", fill: colors.secondary, footer-note)
},
)
grid(
columns: (auto, 1fr, auto),
column-gutter: 12pt,
align: (left + horizon, left + horizon, right + horizon),
_slide-number(colors.secondary),
meta,
if show-logo { aimsight-logo(height: 8mm, on-dark: colors.dark) } else { [] },
)
}
#let _is-release() = sys.inputs.at("release", default: "false") == "true"
#let _is-draft() = sys.inputs.at("draft", default: "false") == "true"
// Generated decks must split slides rather than shrink text. Content taller
// than the slide gets a dashed red frame and a note in drafts, and stops a
// release build (build.py --release).
#let _overflow-guard(body, available) = layout(size => {
let needed = measure(block(width: size.width, body)).height
if needed > available + 1pt {
let excess = str(calc.round((needed - available) / 1mm, digits: 1))
if _is-release() { panic("Slide content is " + excess + " mm too tall: split the slide.") }
[#metadata((family: "presentation", what: "slide", detail: excess + " mm too tall")) <aimsight-overflow>]
// A box of the slide's size, so the label aligns to the slide's right edge.
box(width: size.width, height: available)[
#place(top + left, rect(width: 100%, height: 100%, stroke: (paint: aim-red, thickness: 1.2pt, dash: "dashed")))
#place(top + right, dy: -6mm, text(size: 9pt, weight: "semibold", fill: aim-red)[Overflow +#excess mm: split this slide])
]
}
})
#let _slide-shell(
variant: "light",
source: none,
footer-note: none,
show-footer: true,
show-logo: true,
body,
) = {
let colors = _variant-colors(variant)
// Weak break before each slide avoids a blank trailing page.
pagebreak(weak: true)
block(width: 100%, height: _slide-inner-height)[
#place(
top + left,
dx: -slide-margin-x,
dy: -slide-margin-top,
rect(width: slide-width, height: slide-height, fill: colors.background),
)
// Do not silently clip generated content during validation.
#block(width: 100%, height: _slide-inner-height - 10mm)[
#place(top + left, _overflow-guard(body, _slide-inner-height - 10mm))
#body
]
#if _is-draft() {
place(top + right, dy: -slide-margin-top + 5mm, context text(
size: slide-footer-size, weight: "semibold", tracking: 0.08em, fill: colors.secondary,
)[#term("draft") #sys.inputs.at("revision", default: "")])
}
#if show-footer {
place(
left + bottom,
box(width: 100%)[#_slide-footer(
source: source,
footer-note: footer-note,
variant: variant,
show-logo: show-logo,
)],
)
}
]
}
#let _slide-heading(title, eyebrow: none, variant: "light", subtitle: none) = {
let colors = _variant-colors(variant)
block(width: 100%)[
#if eyebrow != none {
text(size: slide-eyebrow-size, weight: "semibold", tracking: 0.06em, fill: colors.secondary, upper(eyebrow))
v(4pt)
}
#text(size: slide-title-size, weight: "semibold", fill: colors.foreground, title)
#if subtitle != none {
v(4pt)
text(size: slide-body-small-size, fill: colors.secondary, subtitle)
}
#v(6pt)
#line(length: 14%, stroke: 0.8pt + colors.rule-color)
]
}
#let presentation(
title: [AIMsight presentation],
author: [AIMsight SA],
date: datetime.today().display(),
lang: "en",
region: "CH",
font: font-primary,
body,
) = {
set document(title: title, author: if type(author) == str { author } else { () })
set page(
width: slide-width,
height: slide-height,
margin: (
left: slide-margin-x,
right: slide-margin-x,
top: slide-margin-top,
bottom: slide-margin-bottom,
),
header: none,
footer: none,
numbering: none,
)
set text(font: font, size: slide-body-size, fill: ink, lang: lang, region: region, alternates: false)
set par(first-line-indent: 0em, leading: 0.58em, spacing: 0.52em, justify: false)
set list(spacing: 0.45em, indent: 1.0em, body-indent: 0.5em)
show strong: set text(weight: "semibold")
show link: underline
show link: set text(fill: steel)
body
}
#let title-slide(
title: [AIMsight],
subtitle: none,
kicker: none,
hero: none,
variant: "steel",
source: none,
footer-note: none,
) = {
let colors = _variant-colors(variant)
_slide-shell(variant: variant, source: source, footer-note: footer-note, show-footer: false)[
#if hero != none {
place(
right + top,
dx: slide-margin-x,
dy: -slide-margin-top,
box(width: slide-width * 0.46, height: slide-height, clip: true)[
#_visual(hero, width: 100%, height: 100%, fit: "cover")
],
)
}
#block(width: 54%, height: 100%)[
#aimsight-logo(height: 15mm, on-dark: colors.dark)
#v(1fr)
#if kicker != none {
text(size: slide-eyebrow-size, weight: "semibold", tracking: 0.06em, fill: colors.secondary, upper(kicker))
v(5pt)
}
#text(size: slide-cover-title-size, weight: "semibold", fill: colors.foreground, title)
#if subtitle != none { v(8pt)
text(size: slide-cover-subtitle-size, fill: colors.secondary, subtitle) }
#v(1fr)
#aimsight-mark(height: 5mm)
]
]
}
#let section-slide(
title: [Section],
subtitle: none,
index: none,
variant: "deep",
source: none,
footer-note: none,
) = {
let colors = _variant-colors(variant)
_slide-shell(variant: variant, source: source, footer-note: footer-note)[
#v(1fr)
#if index != none { text(size: 13pt, weight: "semibold", fill: colors.secondary, index)
v(5pt) }
#text(size: slide-section-size, weight: "semibold", fill: colors.foreground, title)
#if subtitle != none { v(7pt)
text(size: slide-body-size, fill: colors.secondary, subtitle) }
#v(8pt)
#line(length: 18%, stroke: 1pt + colors.rule-color)
#v(1fr)
]
}
#let statement-slide(
title: [Main claim],
statement: [],
support: none,
eyebrow: none,
variant: "light",
source: none,
footer-note: none,
) = {
let colors = _variant-colors(variant)
_slide-shell(variant: variant, source: source, footer-note: footer-note)[
#_slide-heading(title, eyebrow: eyebrow, variant: variant)
#v(1fr)
#text(size: 27pt, weight: "medium", fill: colors.foreground, statement)
#if support != none { v(10pt)
text(size: slide-body-small-size, fill: colors.secondary, support) }
#v(1fr)
]
}
#let content-slide(
title: [Slide title],
body: [],
eyebrow: none,
subtitle: none,
variant: "light",
source: none,
footer-note: none,
) = {
let colors = _variant-colors(variant)
_slide-shell(variant: variant, source: source, footer-note: footer-note)[
#_slide-heading(title, eyebrow: eyebrow, variant: variant, subtitle: subtitle)
#v(10pt)
#set text(fill: colors.foreground)
#body
]
}
#let two-column-slide(
title: [Slide title],
left: [],
right: [],
ratio: "50-50",
eyebrow: none,
variant: "light",
source: none,
footer-note: none,
) = {
let colors = _variant-colors(variant)
let columns = _ratio-columns(ratio)
_slide-shell(variant: variant, source: source, footer-note: footer-note)[
#_slide-heading(title, eyebrow: eyebrow, variant: variant)
#v(9pt)
#grid(
columns: columns,
column-gutter: slide-column-gutter,
align: top,
[#set text(fill: colors.foreground)
#left],
[#set text(fill: colors.foreground)
#right],
)
]
}
#let image-slide(
title: none,
image: none,
caption: none,
fit: "cover",
variant: "light",
source: none,
footer-note: none,
) = {
let colors = _variant-colors(variant)
_slide-shell(variant: variant, source: source, footer-note: footer-note)[
#if title != none { _slide-heading(title, variant: variant)
v(7pt) }
#let image-height = if title == none { 134mm } else { 105mm }
#block(width: 100%, height: image-height, radius: radius-small, clip: true)[
#_visual(image, width: 100%, height: image-height, fit: fit)
]
#if caption != none { v(4pt)
text(size: slide-caption-size, fill: colors.secondary, caption) }
]
}
#let gallery-slide(
title: [Applications],
images: (),
titles: (),
captions: (),
variant: "light",
source: none,
footer-note: none,
) = {
let colors = _variant-colors(variant)
let n = images.len()
let cols = if n <= 2 { (1fr, 1fr) } else { (1fr, 1fr, 1fr) }
let image-height = if n <= 2 { 76mm } else { 72mm }
_slide-shell(variant: variant, source: source, footer-note: footer-note)[
#_slide-heading(title, variant: variant)
#v(4pt)
#grid(
columns: cols,
column-gutter: 10pt,
row-gutter: 8pt,
..images.enumerate().map(pair => {
let i = pair.first()
let img = pair.last()
let fig-title = if i < titles.len() { titles.at(i) } else { none }
let cap = if i < captions.len() { captions.at(i) } else { none }
block(width: 100%)[
#if fig-title != none {
text(size: 11pt, weight: "semibold", fill: colors.foreground, fig-title)
v(1pt)
}
#block(width: 100%, height: image-height, radius: radius-small, clip: true)[
#_visual(img, width: 100%, height: image-height, fit: "cover")
]
#if cap != none {
v(1pt)
text(size: slide-caption-size, fill: colors.secondary, cap)
}
]
}),
)
]
}
// Plot gallery: unlike photographic galleries, plots are never cropped.
// Each item is a dictionary with at least `image`, plus optional `title`,
// `legend`, and numeric `aspect` (= width / height of the exported figure).
//
// `layout: "auto"` uses the aspect hint for the two cases where geometry
// matters most:
// - one portrait / near-square plot (aspect <= 1.35): figure left, title and
// legend / bullets right;
// - one wider plot: full-width figure with title above and legend below;
// - three plots: a single row only when all aspect hints are <= 1.45;
// otherwise a 2-column overview grid.
//
// Explicit overrides are available for deterministic generated content:
// `single-side`, `single-wide`, `three-row`, `three-grid`, or `auto`.
#let plot-gallery-slide(
title: [Plots],
plots: (),
lead: none,
layout: "auto",
variant: "light",
source: none,
footer-note: none,
) = {
let colors = _variant-colors(variant)
let n = plots.len()
if n < 1 or n > 4 {
panic("plot-gallery-slide supports 1 to 4 plots.")
}
let first-aspect = if n >= 1 { plots.at(0).at("aspect", default: 1.6) } else { 1.6 }
let three-row-auto = if n == 3 {
let a0 = plots.at(0).at("aspect", default: 1.6)
let a1 = plots.at(1).at("aspect", default: 1.6)
let a2 = plots.at(2).at("aspect", default: 1.6)
a0 <= 1.45 and a1 <= 1.45 and a2 <= 1.45
} else { false }
let mode = if layout != "auto" { layout }
else if n == 1 and first-aspect <= 1.35 { "single-side" }
else if n == 1 { "single-wide" }
else if n == 3 and three-row-auto { "three-row" }
else if n == 3 { "three-grid" }
else { "grid" }
if mode != "auto" and mode != "single-side" and mode != "single-wide" and mode != "three-row" and mode != "three-grid" and mode != "grid" {
panic("Unknown plot gallery layout: " + mode + ".")
}
let plot-title-size = if n <= 2 { 12pt } else { 10.5pt }
let plot-legend-size = if n <= 2 { 9.5pt } else { 8.6pt }
let plot-legend(legend, size: plot-legend-size) = {
if legend != none {
block(width: 100%)[
#set text(size: size, fill: colors.secondary)
#set par(leading: 0.52em, spacing: 0.08em, justify: false)
#set list(spacing: 0.12em, indent: 0.9em, body-indent: 0.45em)
#legend
]
}
}
let plot-frame(plot, height) = block(
width: 100%,
height: height,
fill: white,
stroke: rule-thin + colors.rule-color,
inset: 1pt,
)[
#_visual(plot.image, width: 100%, height: height - 2pt, fit: "contain")
]
let stacked-plot(plot, image-height, title-size: plot-title-size, legend-size: plot-legend-size) = {
let plot-title = plot.at("title", default: none)
let legend = plot.at("legend", default: none)
block(width: 100%)[
#if plot-title != none {
text(size: title-size, weight: "semibold", fill: colors.foreground, plot-title)
v(1pt)
}
#plot-frame(plot, image-height)
#if legend != none {
v(1pt)
plot-legend(legend, size: legend-size)
}
]
}
_slide-shell(variant: variant, source: source, footer-note: footer-note)[
#_slide-heading(title, variant: variant)
#if mode == "single-side" {
v(4pt)
let plot = plots.at(0)
let plot-title = plot.at("title", default: none)
let legend = plot.at("legend", default: none)
grid(
columns: (1.08fr, 0.92fr),
column-gutter: slide-column-gutter,
align: top,
[#plot-frame(plot, 118mm)],
[
#if plot-title != none {
text(size: 19pt, weight: "semibold", fill: colors.foreground, plot-title)
}
#if lead != none {
v(4pt)
text(size: 12.5pt, fill: colors.secondary, lead)
}
#if legend != none {
v(7pt)
plot-legend(legend, size: 11pt)
}
],
)
} else {
if lead != none {
v(2pt)
text(size: slide-body-small-size, fill: colors.secondary, lead)
}
v(3pt)
if mode == "single-wide" {
stacked-plot(plots.at(0), 101mm, title-size: 12pt, legend-size: 9.5pt)
} else if mode == "three-row" {
grid(
columns: (1fr, 1fr, 1fr),
column-gutter: 8pt,
align: top,
..plots.map(plot => stacked-plot(plot, 88mm, title-size: 10.5pt, legend-size: 8.5pt)),
)
} else {
let columns = (1fr, 1fr)
let image-height = if n == 2 { 90mm } else { 50mm }
grid(
columns: columns,
column-gutter: 10pt,
row-gutter: 5pt,
align: top,
..plots.map(plot => stacked-plot(plot, image-height)),
)
}
}
]
}
#let metric-slide(
title: [Key figures],
metrics: (),
lead: none,
variant: "light",
source: none,
footer-note: none,
) = {
let colors = _variant-colors(variant)
_slide-shell(variant: variant, source: source, footer-note: footer-note)[
#_slide-heading(title, variant: variant)
#if lead != none { v(6pt)
text(size: slide-body-small-size, fill: colors.secondary, lead) }
#v(1fr)
#grid(
columns: metrics.map(_ => 1fr),
column-gutter: 12pt,
..metrics.map(metric => block(
width: 100%,
inset: (x: 8pt, y: 10pt),
radius: radius-small,
stroke: rule-thin + colors.rule-color,
[
#text(size: slide-metric-size, weight: "semibold", fill: if metric.at("accent", default: false) { if colors.dark { aim-red-on-dark } else { aim-red } } else { colors.foreground })[#metric.value]
#v(4pt)
#text(size: slide-body-small-size, fill: colors.secondary)[#metric.label]
],
)),
)
#v(1fr)
]
}
#let comparison-slide(
title: [Comparison],
left-title: [A],
left: [],
right-title: [B],
right: [],
variant: "light",
source: none,
footer-note: none,
) = {
let colors = _variant-colors(variant)
let panel(panel-title, content) = block(
width: 100%,
height: 102mm,
inset: (x: 9pt, y: 9pt),
radius: radius-small,
stroke: rule-thin + colors.rule-color,
[
#text(size: 17pt, weight: "semibold", fill: colors.foreground, panel-title)
#v(6pt)
#set text(size: slide-body-small-size, fill: colors.foreground)
#content
],
)
_slide-shell(variant: variant, source: source, footer-note: footer-note)[
#_slide-heading(title, variant: variant)
#v(8pt)
#grid(columns: (1fr, 1fr), column-gutter: slide-column-gutter, panel(left-title, left), panel(right-title, right))
]
}
#let architecture-slide(
title: [System architecture],
stages: (),
note: none,
variant: "light",
source: none,
footer-note: none,
) = {
let colors = _variant-colors(variant)
_slide-shell(variant: variant, source: source, footer-note: footer-note)[
#_slide-heading(title, variant: variant)
#v(12pt)
#grid(
columns: stages.map(_ => 1fr),
column-gutter: 10pt,
..stages.enumerate().map(pair => {
let i = pair.first()
let stage = pair.last()
block(width: 100%, height: 82mm)[
#block(
width: 100%,
inset: (x: 7pt, y: 7pt),
radius: radius-small,
stroke: rule-thin + colors.rule-color,
[
#text(size: 11pt, weight: "semibold", fill: colors.secondary)[#numbering("01", i + 1)]
#v(4pt)
#text(size: 15pt, weight: "semibold", fill: colors.foreground)[#stage.title]
#v(4pt)
#text(size: 11pt, fill: colors.secondary)[#stage.detail]
],
)
]
}),
)
#if note != none { v(5pt)
text(size: slide-caption-size, fill: colors.secondary, note) }
]
}
#let timeline-slide(
title: [Workflow],
steps: (),
variant: "light",
source: none,
footer-note: none,
) = {
let colors = _variant-colors(variant)
_slide-shell(variant: variant, source: source, footer-note: footer-note)[
#_slide-heading(title, variant: variant)
#v(14pt)
#grid(
columns: steps.map(_ => 1fr),
column-gutter: 12pt,
..steps.enumerate().map(pair => {
let i = pair.first()
let step = pair.last()
block(width: 100%)[
#circle(radius: 4.2mm, fill: steel)[
#align(center + horizon, text(size: 9pt, weight: "semibold", fill: white)[#(i + 1)])
]
#v(5pt)
#text(size: 14pt, weight: "semibold", fill: colors.foreground)[#step.title]
#v(3pt)
#text(size: 10.5pt, fill: colors.secondary)[#step.detail]
]
}),
)
]
}
#let case-study-slide(
title: [Case study],
image: none,
project: none,
result: none,
facts: (),
variant: "light",
source: none,
footer-note: none,
) = {
let colors = _variant-colors(variant)
_slide-shell(variant: variant, source: source, footer-note: footer-note)[
#_slide-heading(title, eyebrow: project, variant: variant)
#v(7pt)
#grid(
columns: (3fr, 2fr),
column-gutter: slide-column-gutter,
block(width: 100%, height: 98mm, radius: radius-small, clip: true)[#_visual(image, width: 100%, height: 98mm, fit: "cover")],
[
#if result != none { text(size: 18pt, weight: "semibold", fill: colors.foreground, result)
v(8pt) }
#for fact in facts {
text(size: 11pt, weight: "semibold", fill: colors.secondary, fact.label)
linebreak()
text(size: 13pt, fill: colors.foreground, fact.value)
v(6pt)
}
],
)
]
}
#let quote-slide(
quote: [],
attribution: none,
note: none,
variant: "deep",
source: none,
footer-note: none,
) = {
let colors = _variant-colors(variant)
_slide-shell(variant: variant, source: source, footer-note: footer-note)[
#v(1fr)
#text(size: 28pt, weight: "medium", fill: colors.foreground)[“#quote”]
#if attribution != none { v(10pt)
text(size: 13pt, weight: "semibold", fill: colors.secondary, attribution) }
#if note != none { v(3pt)
text(size: 11pt, fill: colors.secondary, note) }
#v(1fr)
]
}
#let closing-slide(
title: [Let's monitor what matters.],
subtitle: none,
contact: auto,
address: auto,
variant: "steel",
source: none,
footer-note: none,
) = {
let colors = _variant-colors(variant)
let contact = if contact == auto { company-address(style: "web") } else { contact }
let address = if address == auto { company-address(style: "postal") } else { address }
_slide-shell(variant: variant, source: source, footer-note: footer-note, show-footer: false)[
#aimsight-logo(height: 15mm, on-dark: colors.dark)
#v(1fr)
#text(size: 36pt, weight: "semibold", fill: colors.foreground, title)
#if subtitle != none { v(8pt)
text(size: 17pt, fill: colors.secondary, subtitle) }
#v(1fr)
#grid(
columns: (auto, 1fr),
column-gutter: 8pt,
align: (left + top, left + top),
aimsight-mark(height: 4.5mm),
[
#text(size: 13pt, weight: "medium", fill: colors.secondary, contact)
#if address != none {
v(3pt)
text(size: 10.5pt, fill: colors.secondary)[
#set par(leading: 0.5em, spacing: 0em, justify: false)
#address
]
}
],
)
]
}
@@ -0,0 +1,617 @@
// ============================================================================
// AIMsight technical/manual template
// One A4 family for manuals, FAQs, reports, white papers and application notes.
// Layout geometry is defined in theme/geometry.typ.
// ============================================================================
#import "../theme/index.typ": *
// Visual baseline: the established AIMsight 10 pt / 11 pt technical documents.
// The unified template preserves their A4 geometry, furniture and callout grammar.
#let _density(density) = {
if density == "compact" {
(
body: technical-compact-body-size,
h1: technical-compact-h1-size,
h2: technical-compact-h2-size,
h3: technical-compact-h3-size,
h4: technical-compact-h4-size,
title: 26pt,
subtitle: 14.5pt,
paragraph-spacing: 1.0em,
table: 9.5pt,
quote: 10.5pt,
)
} else if density == "standard" {
(
body: technical-standard-body-size,
h1: technical-standard-h1-size,
h2: technical-standard-h2-size,
h3: technical-standard-h3-size,
h4: technical-standard-h4-size,
title: 29pt,
subtitle: 14.5pt,
paragraph-spacing: 0.8em,
table: 9.5pt,
quote: 10.5pt,
)
} else {
panic("Unknown technical density: " + density + ". Use compact or standard.")
}
}
// `auto` metadata is stamped by the build from git (tools/build.py):
// --input revision=v1.2.0 / A / v1.2.0-3-gabc1234 --input date=2026-10-28
// --input draft=true --input release=true --input history=<JSON>
#let _from-inputs(value, key, default: none) = {
if value == auto { sys.inputs.at(key, default: default) } else { value }
}
#let _is-release() = sys.inputs.at("release", default: "false") == "true"
// -----------------------------------------------------------------------------
// Callouts
// -----------------------------------------------------------------------------
#let _callout(
label,
body,
accent: rule,
fill: cloud,
label-fill: ink,
border: 0.65pt,
) = block(
width: 100%,
inset: (x: 10pt, y: 8pt),
radius: radius-callout,
stroke: border + accent,
fill: fill,
[
#set text(fill: ink)
#set par(justify: false, leading: 0.58em, spacing: 0.95em)
#text(size: 9pt, weight: "semibold", fill: label-fill)[#label]
#v(3pt)
#body
],
)
// Callout labels follow the document language (see theme/i18n.typ). Safety
// levels escalate amber (caution) -> orange (warning) -> red (danger).
#let note(body) = context _callout(term("note"), body, accent: rule, fill: cloud, label-fill: steel)
#let tip(body) = context _callout(term("tip"), body, accent: data-steel, fill: tip-fill, label-fill: steel)
#let caution(body) = context _callout(term("caution"), body, accent: amber, fill: amber-fill, label-fill: amber, border: 0.8pt)
#let warning(body) = context _callout(term("warning"), body, accent: orange, fill: orange-fill, label-fill: orange, border: 1pt)
#let danger(body) = context _callout(term("danger"), body, accent: aim-red, fill: danger-fill, label-fill: aim-red, border: 1pt)
// -----------------------------------------------------------------------------
// Pictures
// Paths given as strings must be project-root paths ("/documents/x/a.png"):
// Typst resolves a relative string against this template file, not the
// document. For document-relative files pass content: fig(image("a.png")).
// `alt` is the text read by screen readers and kept in tagged PDFs.
// -----------------------------------------------------------------------------
#let _as-visual(source, width: 100%, fit: "contain", alt: none) = {
if type(source) == str or type(source) == bytes { image(source, width: width, fit: fit, alt: alt) }
else { box(width: width, source) }
}
#let fig(source, caption: none, width: 100%, fit: "contain", alt: none) = {
let visual = _as-visual(source, width: width, fit: fit, alt: alt)
if caption == none { figure(visual) } else { figure(visual, caption: caption) }
}
// Two to four pictures side by side under one caption (kit contents,
// before/after, step sequences). Each source is a root path or content;
// `alt` is one text per picture.
#let fig-row(..sources, caption: none, gutter: 8pt, alt: ()) = {
let items = sources.pos()
let row = grid(
columns: (1fr,) * items.len(),
column-gutter: gutter,
align: horizon,
..items.enumerate().map(((i, s)) => _as-visual(s, alt: alt.at(i, default: none))),
)
if caption == none { figure(row) } else { figure(row, caption: caption) }
}
// Software documentation: UI captures get a hairline frame so white UI
// backgrounds do not dissolve into the page.
#let screenshot(source, caption: none, width: 100%, alt: none) = {
let visual = block(
stroke: rule-thin + rule,
radius: radius-small,
clip: true,
_as-visual(source, width: 100%, alt: alt),
)
let framed = box(width: width, visual)
if caption == none { figure(framed) } else { figure(framed, caption: caption) }
}
// A small picture inside a sentence: a toolbar button, a status LED.
#let icon(source, height: 1em, alt: none) = box(
baseline: 15%,
if type(source) == str or type(source) == bytes { image(source, height: height, alt: alt) } else { box(height: height, source) },
)
// -----------------------------------------------------------------------------
// Tables
// -----------------------------------------------------------------------------
// A data table with a shaded header row that repeats after page breaks.
// #data-table(columns: (1fr, 2fr), header: ([Setting], [Effect]), [a], [b], ...)
// `zebra: true` stripes long tables.
#let data-table(columns: auto, header: (), zebra: false, align: left, ..cells) = {
let ncols = if type(columns) == int { columns } else if type(columns) == array { columns.len() } else { header.len() }
let has-header = header.len() > 0
table(
columns: columns,
align: align,
fill: (x, y) => {
if has-header and y == 0 { cloud }
else if zebra and calc.even(y - if has-header { 1 } else { 0 }) == false { zebra-fill }
},
..if has-header {
(table.header(..header.map(h => text(weight: "semibold", fill: steel, h))),)
},
..cells.pos(),
)
}
// -----------------------------------------------------------------------------
// Drafting helpers
// -----------------------------------------------------------------------------
// Marks unfinished content: an amber marker in drafts, a build error in a
// release build (`build.py --release`). Usage: #todo() or #todo[serial number].
#let todo(..args) = {
let body = args.pos().at(0, default: none)
if _is-release() { panic("Unfinished content (#todo) in a release build.") }
context box(
inset: (x: 3pt, y: 1pt),
radius: radius-small,
fill: amber-fill,
stroke: rule-thin + amber,
text(size: 0.85em, weight: "semibold", fill: amber)[#term("todo")#if body != none [: #body]],
)
}
// Reserved space for a figure that does not exist yet (photo to take, capture
// to automate). Keeps the page flow realistic while a document is drafted.
#let placeholder-figure(caption, note: none, height: 52mm) = {
if _is-release() { panic("Placeholder figure in a release build.") }
figure(
block(
width: 100%,
height: height,
fill: cloud,
stroke: 0.65pt + rule,
radius: radius-callout,
align(center + horizon)[
#context text(size: 9pt, weight: "semibold", fill: steel)[#term("todo")]
#if note != none {
v(5pt)
text(size: 8.5pt, fill: quiet, note)
}
],
),
caption: caption,
)
}
// Identification card for a station, system or sensor in reports.
#let summary-card(id, title, meta: none, body) = block(
width: 100%,
inset: (x: 10pt, y: 8pt),
radius: radius-callout,
stroke: 0.65pt + rule,
fill: cloud,
breakable: false,
grid(
columns: (18mm, 1fr),
gutter: 8pt,
text(size: 17pt, weight: "semibold", fill: steel, id),
[
#text(weight: "semibold", fill: ink, title)
#if meta != none [\ #text(size: 9pt, fill: quiet, meta)]
#v(2pt)
#body
],
),
)
// -----------------------------------------------------------------------------
// Revision history
// Entries come from the git tags of the document (build.py passes them as
// --input history=<JSON>) or are given explicitly:
// #revision-history(entries: ((revision: "A", date: "2026-10-19",
// description: [First issue], author: [M. Lany]),))
// -----------------------------------------------------------------------------
#let revision-history(entries: auto) = {
let rows = if entries == auto {
let raw = sys.inputs.at("history", default: none)
if raw == none { () } else { json(bytes(raw)) }
} else { entries }
if rows.len() == 0 { return [] }
context data-table(
columns: (auto, auto, 1fr, auto),
header: (term("revision"), term("date"), term("description"), term("author")),
..rows.map(r => (
[#r.at("revision", default: "")],
format-date(r.at("date", default: "")),
[#r.at("description", default: "")],
[#r.at("author", default: "")],
)).flatten(),
)
}
// -----------------------------------------------------------------------------
// Running furniture
// -----------------------------------------------------------------------------
#let _classification-label(classification) = {
if classification == none { none }
else if classification in ("public", "internal", "confidential", "restricted") { term(classification) }
else { panic("Unknown classification: " + classification + ". Use public, internal, confidential or restricted.") }
}
#let _running-header(label, logo) = context {
// Physical page, not the logical page counter: the counter restarts after
// the table of contents and must not bring the header back on page 1.
if here().page() > 1 {
let label-content = if label == none { [] } else {
text(size: 8.5pt, weight: "medium", fill: data-steel, label)
}
v(technical-running-header-top-gap)
move(dy: technical-running-header-dy)[
#block(width: 100%)[
#grid(
columns: (1fr, auto),
gutter: 10pt,
align: (left + horizon, right + horizon),
label-content,
resolve-logo(logo, width: technical-running-logo-width),
)
]
]
line(length: 100%, stroke: rule-thin + rule)
}
}
#let _running-footer(
revision,
document-id: none,
classification: none,
address-mode: "end",
footer-address: none,
) = context {
line(length: 100%, stroke: 0.35pt + rule)
v(4pt)
let ident = ()
if document-id != none { ident.push(document-id) }
if revision != none { ident.push([#term("revision") #revision]) }
let ident-content = text(size: 8pt, fill: quiet, ident.join[ · ])
let class-label = _classification-label(classification)
let class-content = if class-label == none { [] } else {
text(size: 7.6pt, weight: "semibold", tracking: 0.06em, fill: steel, class-label)
}
// Uses the page numbering in force: roman in front matter, arabic in the body.
let page-content = text(size: 8.5pt, fill: quiet, counter(page).display())
if address-mode == "footer" and footer-address != none {
grid(
columns: (1fr, auto, auto, auto),
column-gutter: 12pt,
align: (left + horizon, right + horizon, right + horizon, right + horizon),
text(size: 7.2pt, fill: quiet, footer-address),
class-content,
ident-content,
page-content,
)
} else {
grid(
columns: (1fr, auto, 1fr),
align: (left + horizon, center + horizon, right + horizon),
ident-content,
class-content,
page-content,
)
}
}
// -----------------------------------------------------------------------------
// End-of-document address
// Intent: the address always sits at the bottom of the last page. It stays
// on the page where the body ends when it fits below the body; otherwise it
// goes to the bottom of one extra page, even if that page is otherwise empty.
// The zero-height blocks around it are anchors for tests/end_address.py.
// -----------------------------------------------------------------------------
#let _end-address-block(address) = {
let address-text = align(center, text(size: 7.8pt, fill: quiet)[
#set par(leading: 0.48em, spacing: 0em, justify: false)
#address
])
let available-width = technical-page-width - technical-margin-left - technical-margin-right
let address-height = measure(address-text, width: available-width).height
let anchor = locate(<aimsight-end-address>)
let y = anchor.position().y
let body-bottom = technical-page-height - technical-margin-bottom
// Footnotes on that page sit between the body and the bottom margin.
// Over-estimate their room (separator + generous line height): the worst
// case is then an extra page, never an address squeezed into the notes.
let notes = query(footnote).filter(f => f.location().page() == anchor.page())
let notes-room = if notes.len() == 0 { 0pt } else {
2em.to-absolute() + notes.map(f => measure(text(size: technical-footnote-size, f.body), width: available-width).height + 0.8em.to-absolute()).sum()
}
let reserve = address-height + 5mm
if body-bottom - notes-room - y < reserve {
pagebreak()
}
// Filler and address form one unbreakable block of the remaining height,
// so they can never be separated by a page break.
block(
width: 100%,
height: 1fr,
breakable: false,
above: 0pt,
below: 0pt,
align(bottom, {
[#block(height: 0pt, above: 0pt, below: 0pt, width: 100%) <aimsight-address-top>]
address-text
[#block(height: 0pt, above: 0pt, below: 0pt, width: 100%) <aimsight-address-bottom>]
}),
)
}
#let _adaptive-end-address(address) = {
// Measure where the body ends with a separate anchor. `here()` inside the
// context below would report the position of its own output, which sits at
// the page bottom after `v(1fr)`; the room test then always failed.
// A zero-height block, not a metadata tag: tags travel with the next
// element, so the anchor would follow the page break and oscillate.
[#block(height: 0pt, above: 0pt, below: 0pt, width: 100%) <aimsight-end-address>]
context _end-address-block(address)
}
// -----------------------------------------------------------------------------
// Metadata helpers
// -----------------------------------------------------------------------------
// Accepts a name, a (name: ...) dictionary or an array of either.
#let _author-names(authors) = {
if authors == none { return () }
let list = if type(authors) == array { authors } else { (authors,) }
list.map(a => if type(a) == dictionary { a.at("name", default: none) } else { a }).filter(a => a != none)
}
#let _plain(value) = {
if value == none { none }
else if type(value) == str { value }
else if type(value) == content and value.has("text") { value.text }
else if type(value) == content and value.has("children") { value.children.map(_plain).filter(v => v != none).join("") }
else if type(value) == content and value.has("body") { _plain(value.body) }
else if type(value) == content and value.func() == [ ].func() { " " }
else { none }
}
// -----------------------------------------------------------------------------
// Document
// -----------------------------------------------------------------------------
#let technical-document(
title: none,
subtitle: none,
authors: ((name: [AIMsight]),),
date: auto,
revision: auto,
draft: auto,
venue: none,
abstract: none,
document-label: none,
// Document control: identifier, classification (public, internal,
// confidential, restricted) and approver, printed on page 1 and in the footer.
document-id: none,
classification: none,
approved-by: none,
lang: "en",
region: "CH",
density: "standard",
font: font-primary,
justify-text: false,
section-numbering: true,
show-toc: true,
toc-depth: 3,
pagebreak-before-toc: false,
logo: auto,
show-address: true,
address-mode: "end",
address: auto,
footer-address: auto,
body,
) = {
let sizes = _density(density)
let effective-address-mode = if show-address { address-mode } else { "none" }
if effective-address-mode != "end" and effective-address-mode != "footer" and effective-address-mode != "none" {
panic("Unknown address mode: " + effective-address-mode + ". Use end, footer or none.")
}
let date = _from-inputs(date, "date", default: datetime.today())
let revision = _from-inputs(revision, "revision")
let draft = _from-inputs(draft, "draft", default: "false")
let is-draft = draft == true or draft == "true"
let address = if address == auto { company-address(style: "block") } else { address }
let footer-address = if footer-address == auto { company-address(style: "line") } else { footer-address }
let author-names = _author-names(authors)
let plain-title = _plain(title)
let plain-authors = author-names.map(_plain).filter(a => a != none)
set document(
title: if plain-title == none { none } else { plain-title },
author: plain-authors,
)
set page(
width: technical-page-width,
height: technical-page-height,
margin: (
left: technical-margin-left,
top: technical-margin-top,
right: technical-margin-right,
bottom: technical-margin-bottom,
),
// Front matter (title + contents) is numbered i, ii; the body restarts at 1.
numbering: if show-toc { "i" } else { "1" },
header: _running-header(document-label, logo),
footer: _running-footer(
revision,
document-id: document-id,
classification: classification,
address-mode: effective-address-mode,
footer-address: footer-address,
),
footer-descent: 25%,
background: if is-draft {
context rotate(-40deg, text(size: 96pt, weight: "bold", fill: rule.transparentize(55%), term("draft")))
},
)
set text(
lang: lang,
region: region,
font: font,
size: sizes.body,
fill: ink,
alternates: false,
)
set par(
first-line-indent: 0em,
leading: 0.64em,
justify: justify-text,
spacing: sizes.paragraph-spacing,
)
set list(spacing: 0.6em, indent: 1.2em, body-indent: 0.55em)
set enum(number-align: start, spacing: 0.6em, indent: 1.2em, body-indent: 0.55em)
show heading: set text(hyphenate: false)
show heading.where(level: 1): set text(size: sizes.h1, weight: "semibold", fill: ink)
show heading.where(level: 1): set block(above: 20pt, below: 10pt)
show heading.where(level: 2): set text(size: sizes.h2, weight: "semibold", fill: steel)
show heading.where(level: 2): set block(above: 12pt, below: 8pt)
show heading.where(level: 3): set text(size: sizes.h3, weight: "semibold", fill: ink)
show heading.where(level: 3): set block(above: 11pt, below: 6pt)
show heading.where(level: 4): set text(size: sizes.h4, weight: "semibold", fill: steel)
show heading.where(level: 4): set block(above: 9pt, below: 4pt)
// A set rule inside `if { ... }` only lives in that block; the conditional
// form applies it to the whole document.
set heading(numbering: "1.1.1") if section-numbering
// Contents: chapters stand out, sub-entries stay compact so a long report
// keeps its contents on one page.
show outline.entry.where(level: 1): set block(above: 0.75em)
show outline.entry.where(level: 1): set text(weight: "medium")
show outline.entry: set block(below: 0.3em)
set quote(block: true)
show quote: set block(inset: (left: 10pt), above: 6pt, below: 6pt)
show quote: set par(leading: 0.6em, spacing: 0.4em)
show quote: set text(size: sizes.quote, style: "italic", fill: quiet)
// Figures centre their content; images keep their own size so icons can
// sit inside a sentence (use #fig / #screenshot for block pictures).
set figure(gap: 0.45em, supplement: none)
show figure.caption: set text(size: technical-caption-size, fill: quiet)
show figure.caption: set par(justify: false, leading: 0.5em)
show raw: set block(inset: (x: 9pt, y: 6pt), radius: radius-callout, fill: cloud)
show raw: set text(fill: ink, size: technical-code-size)
set table(inset: (x: 6pt, y: 4.5pt), stroke: rule-thin + rule)
show table.cell: set text(size: sizes.table)
show table.cell: set par(justify: false, leading: 0.52em, spacing: 0.25em)
set footnote.entry(indent: 0.5em)
show footnote.entry: set par(hanging-indent: 1em, leading: 0.5em)
show footnote.entry: set text(size: technical-footnote-size, fill: quiet)
show link: underline
show link: set text(fill: steel)
move(dy: technical-first-header-dy)[
#block(width: 100%)[
#grid(
columns: (1fr, auto),
gutter: 12pt,
align: (left + horizon, right + horizon),
if document-label == none { [] } else {
text(size: 9pt, weight: "semibold", fill: data-steel, document-label)
},
resolve-logo(logo, width: technical-first-logo-width),
)
]
]
v(20pt)
if title != none {
align(left, text(size: sizes.title, weight: "semibold", fill: ink)[
#set par(justify: false, leading: 0.28em, spacing: 0em)
#title
])
}
if subtitle != none {
v(12pt)
align(left, text(size: sizes.subtitle, fill: data-steel)[
#set par(justify: false, leading: 0.45em, spacing: 0em)
#subtitle
])
}
v(8pt)
line(length: 100%, stroke: 0.8pt + rule)
v(8pt)
let meta(body) = text(size: 9.5pt, fill: quiet, body)
let author-content = if author-names.len() == 0 { [] } else { meta(author-names.join[, ]) }
let revision-content = if revision == none { [] } else { context meta[#term("revision") #revision] }
grid(
columns: (1fr, 1fr, 1fr),
column-gutter: 12pt,
align: (left, center, right),
context meta(format-date(date)),
author-content,
revision-content,
)
if document-id != none or classification != none or approved-by != none {
v(5pt)
context grid(
columns: (1fr, 1fr, 1fr),
column-gutter: 12pt,
align: (left, center, right),
if document-id == none { [] } else { meta[#term("document") #document-id] },
if approved-by == none { [] } else { meta[#term("approved-by") #approved-by] },
{
let label = _classification-label(classification)
if label == none { [] } else { text(size: 9pt, weight: "semibold", tracking: 0.06em, fill: steel, label) }
},
)
}
if venue != none {
v(5pt)
meta(venue)
}
if abstract != none {
v(16pt)
context _callout(term("abstract"), abstract, accent: rule, fill: cloud, label-fill: steel)
}
if pagebreak-before-toc and show-toc { pagebreak() }
if show-toc {
v(16pt)
outline(indent: auto, depth: toc-depth)
pagebreak()
}
set page(numbering: "1") if show-toc
counter(page).update(1)
body
if effective-address-mode == "end" and address != none {
_adaptive-end-address(address)
}
}
+46
View File
@@ -0,0 +1,46 @@
// AIMsight shared colour system
// Red is semantic and intentionally scarce.
#let aim-red = rgb("#E41D25")
// AIMsight red for text on steel/deep surfaces, where #E41D25 falls to about
// 2.1:1 contrast; this tint keeps 3.5:1 on steel and 5.8:1 on slide-deep
// (large text, so above the 3:1 minimum).
#let aim-red-on-dark = rgb("#FF6B6F")
#let ink = rgb("#252D33")
#let graphite = rgb("#39434A")
#let quiet = rgb("#657980")
#let white = rgb("#FFFFFF")
#let steel = rgb("#074A5E")
#let data-steel = rgb("#5992AD")
#let deep-steel = rgb("#023D51")
// Presentation-only deep contrast surface. Intentionally darker than the
// brochure rail so section slides are clearly distinct from title slides.
#let slide-deep = rgb("#10232D")
#let cloud = rgb("#F4F7F8")
#let rule = rgb("#B8CDD5")
#let green = rgb("#2F7D68")
// Brochure supporting surfaces.
#let brochure-side-light = rgb("#F4F7F8")
#let brochure-side-dark = deep-steel
#let brochure-side-dark-soft = rgb("#D9EBF1")
#let brochure-side-dark-rule = rgb("#8DB7C5")
#let brochure-cover-light-band = rgb("#D9EBF1")
#let brochure-cover-light-rule = rgb("#8DB7C5")
// Technical-document semantic colours. Safety levels follow the ISO 3864 /
// ANSI Z535 order: caution amber < warning orange < danger red. All three
// label colours reach 4.2:1 or more on white.
#let amber = rgb("#A96F18")
#let amber-fill = rgb("#FFF8E8")
#let orange = rgb("#C2560F")
#let orange-fill = rgb("#FFF3EA")
#let danger-fill = rgb("#FFF1F2")
#let tip-fill = rgb("#EAF4F7")
// Light zebra striping for long data tables.
#let zebra-fill = rgb("#F9FBFB")
+35
View File
@@ -0,0 +1,35 @@
// Company identity used by every template: change the address here once.
#let company = (
name: "AIMsight SA",
street: "Route de Cité-Ouest 2",
postcode: "1196",
city: "Gland",
country: (en: "Switzerland", fr: "Suisse", de: "Schweiz", es: "Suiza", it: "Svizzera"),
email: "info@aimsight.ch",
web: "aimsight.ch",
)
// The company address in the document language. Call inside `context` or
// let the caller's context resolve it (it is contextual itself).
// style: "block" four lines (end-of-document address, letters)
// "line" one line with middle dots (running footer)
// "postal" name, then street · city · country (closing slides, contact blocks)
// "web" "aimsight.ch · info@aimsight.ch" (slides, brochure footers)
#let company-address(style: "block") = context {
let country = company.country.at(text.lang, default: company.country.en)
if style == "block" [
#company.name\
#company.street\
#company.postcode #company.city, #country\
#company.email
] else if style == "line" [
#company.name · #company.street · #company.postcode #company.city · #company.email
] else if style == "postal" [
#company.name\
#company.street · #company.postcode #company.city · #country
] else if style == "web" [
#company.web · #company.email
] else {
panic("Unknown company-address style: " + style + ". Use block, line, postal or web.")
}
}
+84
View File
@@ -0,0 +1,84 @@
// AIMsight shared geometry and layout settings.
// Edit this file to tune page geometry. Content documents should not contain
// millimetre/point nudges for template furniture.
// -----------------------------------------------------------------------------
// Shared geometry language
// -----------------------------------------------------------------------------
#let radius-small = 1.5pt
#let radius-callout = 3pt
#let rule-thin = 0.45pt
#let rule-medium = 0.75pt
#let rule-strong = 1pt
// -----------------------------------------------------------------------------
// A4 brochure
// -----------------------------------------------------------------------------
#let brochure-page-width = 210mm
#let brochure-page-height = 297mm
#let brochure-margin-left = 21mm
#let brochure-margin-right = 15mm
#let brochure-margin-top = 19mm
#let brochure-margin-bottom = 16mm
#let brochure-sidebar-width = 54mm
#let brochure-sidebar-band-width = 72mm
#let brochure-column-gutter = 9mm
#let brochure-sidebar-content-dx = 3mm
// Canonical cover geometry: the former "concept-last" layout.
#let brochure-cover-title-band-height = 36mm
#let brochure-cover-hero-height = 68mm
#let brochure-cover-header-to-band-dy = 0mm
#let brochure-cover-band-to-hero-dy = -0.18mm
#let brochure-cover-hero-to-body-gap = 3mm
#let brochure-cover-title-text-dy = 0.35mm
#let brochure-cover-strapline-dy = -0.25mm
// Cover rail header. These values reproduce the accepted final rendering.
#let brochure-cover-rail-content-dx = brochure-sidebar-content-dx
#let brochure-cover-rail-top-dy = -6mm
#let brochure-cover-rail-edition-rule-gap = 4.5pt
#let brochure-cover-rail-rule-context-gap = 6pt
#let brochure-cover-rail-context-dy = -0.4mm
#let brochure-cover-rail-rule-thickness = 0.45pt
// Cover framing. Strokes are overlays and consume no layout height.
#let brochure-cover-frame-thickness = 0.55pt
#let brochure-cover-separator-thickness = 0.45pt
#let brochure-cover-accent-thickness = 1.15pt
#let brochure-cover-top-frame-dy = 0mm
#let brochure-cover-band-separator-dy = 0mm
#let brochure-cover-hero-separator-dy = 0mm
#let brochure-cover-hero-bottom-frame-dy = 0mm
// -----------------------------------------------------------------------------
// A4 technical/manual
// -----------------------------------------------------------------------------
#let technical-page-width = 210mm
#let technical-page-height = 297mm
#let technical-margin-left = 24mm
#let technical-margin-right = 24mm
#let technical-margin-top = 18mm
#let technical-margin-bottom = 18mm
// Running-header / first-page optical tuning.
#let technical-running-header-top-gap = 4pt
#let technical-running-header-dy = 2mm
#let technical-running-logo-width = 27mm
#let technical-first-header-dy = -2mm
#let technical-first-logo-width = 34mm
// -----------------------------------------------------------------------------
// 16:9 presentation
// -----------------------------------------------------------------------------
#let slide-height = 190.5mm
#let slide-width = slide-height * 16 / 9
#let slide-margin-x = 22mm
#let slide-margin-top = 16mm
#let slide-margin-bottom = 6mm
#let slide-column-gutter = 14mm
#let slide-rule-offset = 9mm
// Brochure final-page contact furniture.
#let brochure-final-contact-reserve = 24mm
#let brochure-final-contact-dy = -5mm
+72
View File
@@ -0,0 +1,72 @@
// Fixed template wording and date formatting, keyed by `text.lang`.
// Signal words follow the usual ISO 3864 / ANSI Z535 wording per language.
// Unknown languages fall back to English.
#let _strings = (
en: (
note: "NOTE", tip: "TIP", caution: "CAUTION", warning: "WARNING", danger: "DANGER",
abstract: "ABSTRACT", revision: "Revision", draft: "DRAFT", todo: "TO DO",
document: "Document", approved-by: "Approved by", classification: "Classification",
revision-history: "Revision history", date: "Date", description: "Description", author: "Author",
public: "PUBLIC", internal: "INTERNAL", confidential: "CONFIDENTIAL", restricted: "RESTRICTED",
),
fr: (
note: "REMARQUE", tip: "CONSEIL", caution: "ATTENTION", warning: "AVERTISSEMENT", danger: "DANGER",
abstract: "RÉSUMÉ", revision: "Révision", draft: "PROJET", todo: "À COMPLÉTER",
document: "Document", approved-by: "Approuvé par", classification: "Classification",
revision-history: "Historique des révisions", date: "Date", description: "Description", author: "Auteur",
public: "PUBLIC", internal: "INTERNE", confidential: "CONFIDENTIEL", restricted: "DIFFUSION RESTREINTE",
),
de: (
note: "HINWEIS", tip: "TIPP", caution: "VORSICHT", warning: "WARNUNG", danger: "GEFAHR",
abstract: "ZUSAMMENFASSUNG", revision: "Revision", draft: "ENTWURF", todo: "ZU ERGÄNZEN",
document: "Dokument", approved-by: "Freigegeben von", classification: "Klassifizierung",
revision-history: "Revisionsverlauf", date: "Datum", description: "Beschreibung", author: "Autor",
public: "ÖFFENTLICH", internal: "INTERN", confidential: "VERTRAULICH", restricted: "STRENG VERTRAULICH",
),
es: (
note: "NOTA", tip: "CONSEJO", caution: "PRECAUCIÓN", warning: "ADVERTENCIA", danger: "PELIGRO",
abstract: "RESUMEN", revision: "Revisión", draft: "BORRADOR", todo: "POR COMPLETAR",
document: "Documento", approved-by: "Aprobado por", classification: "Clasificación",
revision-history: "Historial de revisiones", date: "Fecha", description: "Descripción", author: "Autor",
public: "PÚBLICO", internal: "INTERNO", confidential: "CONFIDENCIAL", restricted: "RESTRINGIDO",
),
it: (
note: "NOTA", tip: "SUGGERIMENTO", caution: "ATTENZIONE", warning: "AVVERTENZA", danger: "PERICOLO",
abstract: "SINTESI", revision: "Revisione", draft: "BOZZA", todo: "DA COMPLETARE",
document: "Documento", approved-by: "Approvato da", classification: "Classificazione",
revision-history: "Cronologia delle revisioni", date: "Data", description: "Descrizione", author: "Autore",
public: "PUBBLICO", internal: "INTERNO", confidential: "CONFIDENZIALE", restricted: "RISERVATO",
),
)
// Must be called inside `context`.
#let term(key) = {
let table = _strings.at(text.lang, default: _strings.en)
table.at(key, default: _strings.en.at(key))
}
#let _months = (
en: ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"),
fr: ("janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"),
de: ("Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"),
es: ("enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"),
it: ("gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"),
)
// "2026-10-28" or a datetime -> "28 October 2026" / "28 octobre 2026" /
// "28. Oktober 2026" / "28 de octubre de 2026" / "28 ottobre 2026". Anything else is returned as given,
// so free text such as [July 2026] keeps working. Must be called in `context`.
#let format-date(value) = {
let d = value
if type(value) == str and value.match(regex("^\d{4}-\d{2}-\d{2}$")) != none {
let parts = value.split("-").map(int)
d = datetime(year: parts.at(0), month: parts.at(1), day: parts.at(2))
}
if type(d) != datetime { return value }
let months = _months.at(text.lang, default: _months.en)
let month = months.at(d.month() - 1)
if text.lang == "de" { [#d.day(). #month #d.year()] }
else if text.lang == "es" { [#d.day() de #month de #d.year()] }
else { [#d.day() #month #d.year()] }
}
+6
View File
@@ -0,0 +1,6 @@
#import "colors.typ": *
#import "geometry.typ": *
#import "typography.typ": *
#import "logo.typ": *
#import "company.typ": *
#import "i18n.typ": term, format-date
+38
View File
@@ -0,0 +1,38 @@
// Canonical AIMsight logo assets.
//
// The logos are read as bytes relative to this file, so the brand keeps
// working wherever it is placed (repository root, vendored `brand/` folder of
// a document factory, or a Typst package). Never refer to the logos through a
// project-root path such as "/assets/logos/...".
#let default-logo = read("../assets/logos/AIMsight_logo_lg.svg", encoding: none)
#let default-logo-reversed = read("../assets/logos/AIMsight_logo_lg_reversed.svg", encoding: none)
#let default-mark = read("../assets/logos/AIMsight_mark.svg", encoding: none)
// Kept for 0.x documents that passed `logo: default-logo-path` explicitly.
#let default-logo-path = default-logo
#let default-mark-path = default-mark
// `on-dark: true` selects the white-wordmark variant for steel/deep surfaces;
// the grey wordmark of the standard logo is below 3:1 contrast there.
#let aimsight-logo(height: 9.5mm, width: auto, on-dark: false) = image(
if on-dark { default-logo-reversed } else { default-logo },
height: if width == auto { height } else { auto },
width: width,
fit: "contain",
)
#let aimsight-mark(height: 4mm) = image(
default-mark,
height: height,
fit: "contain",
)
// Resolve a template `logo:` argument.
// auto -> AIMsight logo, none -> nothing, bytes -> image data,
// str -> project-root path ("/assets/client-logo.svg"), content -> as given.
#let resolve-logo(logo, height: auto, width: auto, on-dark: false) = {
if logo == none { [] }
else if logo == auto { aimsight-logo(height: height, width: width, on-dark: on-dark) }
else if type(logo) == bytes or type(logo) == str { image(logo, height: height, width: width, fit: "contain") }
else { box(height: height, width: width, logo) }
}
@@ -0,0 +1,44 @@
// AIMsight typography
// Inter is the validated family for editorial, technical, web and cloud use.
// Font files are intentionally not bundled.
#let font-primary = "Inter"
// Brochure
#let brochure-body-size = 10pt
#let brochure-h1-size = 15.5pt
#let brochure-h2-size = 13pt
#let brochure-h3-size = 10.5pt
#let brochure-caption-size = 7.8pt
#let brochure-small-size = 7.3pt
#let brochure-cover-title-size = 28pt
#let brochure-cover-title-weight = "bold"
// Technical/manual
#let technical-compact-body-size = 10pt
#let technical-compact-h1-size = 15.5pt
#let technical-compact-h2-size = 13pt
#let technical-compact-h3-size = 12pt
#let technical-compact-h4-size = 11pt
#let technical-standard-body-size = 11pt
#let technical-standard-h1-size = 17pt
#let technical-standard-h2-size = 14pt
#let technical-standard-h3-size = 12pt
#let technical-standard-h4-size = 11pt
#let technical-caption-size = 9pt
#let technical-code-size = 9pt
#let technical-footnote-size = 9pt
// Presentation
#let slide-body-size = 18pt
#let slide-body-small-size = 15pt
#let slide-title-size = 31pt
#let slide-section-size = 38pt
#let slide-cover-title-size = 44pt
#let slide-cover-subtitle-size = 20pt
#let slide-metric-size = 36pt
#let slide-caption-size = 10.5pt
#let slide-footer-size = 8.5pt
#let slide-eyebrow-size = 10pt
+122
View File
@@ -0,0 +1,122 @@
#!/usr/bin/env python3
"""Vendor the AIMsight brand into a document factory and keep it frozen.
From a brand checkout (this repository):
python tools/brand.py install <factory-dir>
From a factory root:
python brand/tools/brand.py check # vendored files unmodified?
python brand/tools/brand.py update v1.1.0 # replace brand/ with that tag
`install` copies only what documents need (templates, theme, logos, compat,
tools, docs) into <factory>/brand/ and writes brand/MANIFEST.sha256. `check`
fails when a vendored file was edited locally: brand changes go through the
brand repository and a new tag, never through a factory or a document repo.
"""
from __future__ import annotations
import hashlib
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
BRAND_ROOT = Path(__file__).resolve().parent.parent
VENDORED = ["VERSION", "typst.toml", "lib.typ", "README.md", "CHANGELOG.md", "theme", "templates", "starters",
"compat", "assets/logos", "tools", "docs", "fonts"]
DEFAULT_REPO = "gitea@exchange.sensima.ch:AIMsight/aimsight-typst.git"
MANIFEST = "MANIFEST.sha256"
def files_under(root: Path) -> list[Path]:
out = []
for entry in VENDORED:
p = root / entry
if p.is_file():
out.append(p)
elif p.is_dir():
out += [f for f in p.rglob("*") if f.is_file() and "__pycache__" not in f.parts]
return sorted(out)
def digest(path: Path) -> str:
# Hash with normalised line endings so a Windows checkout (autocrlf) and a
# Linux CI runner agree.
data = path.read_bytes()
if b"\0" not in data[:1024]:
data = data.replace(b"\r\n", b"\n")
return hashlib.sha256(data).hexdigest()
def install(target_factory: Path) -> None:
dest = target_factory / "brand"
if dest.exists():
shutil.rmtree(dest)
lines = []
for src in files_under(BRAND_ROOT):
rel = src.relative_to(BRAND_ROOT)
out = dest / rel
out.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, out)
lines.append(f"{digest(out)} {rel.as_posix()}")
(dest / MANIFEST).write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n")
version = (BRAND_ROOT / "VERSION").read_text().strip()
print(f"brand {version} installed into {dest} ({len(lines)} files)")
def check(factory: Path) -> int:
brand = factory / "brand"
manifest = brand / MANIFEST
if not manifest.exists():
print("brand: no MANIFEST.sha256; brand/ was not installed with tools/brand.py")
return 1
expected = {}
for line in manifest.read_text(encoding="utf-8").splitlines():
if line.strip():
h, rel = line.split(" ", 1)
expected[rel] = h
bad = []
for rel, h in expected.items():
f = brand / rel
if not f.exists():
bad.append(f"missing brand/{rel}")
elif digest(f) != h:
bad.append(f"modified brand/{rel}")
actual = {f.relative_to(brand).as_posix() for f in brand.rglob("*")
if f.is_file() and f.name != MANIFEST and "__pycache__" not in f.parts}
bad += [f"added brand/{rel}" for rel in sorted(actual - set(expected))]
if bad:
print("brand: vendored files differ from the released brand:")
print("\n".join(" " + b for b in bad))
print("Propose the change in the brand repository and run `brand.py update <tag>`.")
return 1
version = (brand / "VERSION").read_text().strip()
print(f"brand {version}: {len(expected)} vendored files unmodified")
return 0
def update(factory: Path, ref: str, repo: str) -> int:
with tempfile.TemporaryDirectory() as tmp:
res = subprocess.run(["git", "clone", "--quiet", "--depth", "1", "--branch", ref, repo, tmp])
if res.returncode != 0:
print(f"brand: cannot fetch {ref} from {repo}")
return 1
return subprocess.run([sys.executable, str(Path(tmp) / "tools" / "brand.py"), "install", str(factory)]).returncode
def main(argv: list[str]) -> int:
if len(argv) >= 2 and argv[0] == "install":
install(Path(argv[1]).resolve())
return 0
if argv[:1] == ["check"]:
return check(Path.cwd())
if len(argv) >= 2 and argv[0] == "update":
repo = argv[2] if len(argv) > 2 else DEFAULT_REPO
return update(Path.cwd(), argv[1], repo)
print(__doc__)
return 2
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+244
View File
@@ -0,0 +1,244 @@
#!/usr/bin/env python3
"""Compile the documents of an AIMsight document factory.
Run from the factory root (the folder that contains `brand/` and
`documents/`):
python brand/tools/build.py # every document and language
python brand/tools/build.py station-manual # one document, all languages
python brand/tools/build.py station-manual:fr # one language
python brand/tools/build.py --png # page images for reviews
python brand/tools/build.py --watch faq:fr # rebuild on every save
python brand/tools/build.py --release # PDF/A, refuses drafts and TODOs
Documents live in documents/<slug>/main.typ. Translations sit next to it as
main.<lang>.typ (main.fr.typ, main.es.typ, ...) and share the folder's
images; they build to <slug>-<lang>.pdf.
Each PDF is stamped from git, so its footer says which sources produced it:
revision tag on HEAD: v1.2.0 -> "1.2.0", rev-B -> "B";
after a tag: "1.2.0-3-gabc1234"; uncommitted changes: "+local"
date date of the HEAD commit, today without git
draft false only for a clean tree exactly on a tag (DRAFT watermark otherwise)
history every tag of the document, for #revision-history()
Tags are per document (station-manual/v1.5.0, station-manual/rev-A) or global
(v1.5.0, rev-A); per-document tags win.
Standard library only (Python 3.11+). Requires `typst` on PATH.
"""
from __future__ import annotations
import argparse
import datetime as dt
import json
import re
import shutil
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
ROOT = Path.cwd()
TOOLS = Path(__file__).resolve().parent
BRAND = TOOLS.parent
LANG_FILE = re.compile(r"^main\.([a-z]{2})\.typ$")
FONT_WARNING = re.compile(r"unknown font family", re.I)
@dataclass
class Doc:
slug: str
lang: str | None # None for main.typ
path: Path
variants: bool # the folder has translations
@property
def ident(self) -> str:
return self.slug if self.lang is None else f"{self.slug}:{self.lang}"
@property
def output_stem(self) -> str:
if not self.variants:
return self.slug
return f"{self.slug}-{self.lang or source_lang(self.path)}"
def source_lang(path: Path) -> str:
m = re.search(r'\blang:\s*"([a-z]{2})"', path.read_text(encoding="utf-8"))
return m.group(1) if m else "en"
def git(*args: str) -> str | None:
try:
out = subprocess.run(["git", *args], cwd=ROOT, capture_output=True, text=True, check=True)
except (OSError, subprocess.CalledProcessError):
return None
return out.stdout.strip()
def find_documents(selection: list[str] | None = None) -> list[Doc]:
docs = []
for folder in sorted(p for p in (ROOT / "documents").glob("*") if (p / "main.typ").exists()):
langs = sorted(m.group(1) for f in folder.iterdir() if (m := LANG_FILE.match(f.name)))
docs.append(Doc(folder.name, None, folder / "main.typ", bool(langs)))
docs += [Doc(folder.name, lang, folder / f"main.{lang}.typ", True) for lang in langs]
if selection:
picked = []
for item in selection:
slug, _, lang = item.partition(":")
match = [d for d in docs if d.slug == slug and (not lang or (d.lang or source_lang(d.path)) == lang)]
if not match:
sys.exit(f"Unknown document: {item}")
picked += match
docs = picked
return docs
def _tag_patterns(slug: str) -> list[str]:
return [f"{slug}/v*", f"{slug}/rev-*", "v*", "rev-*"]
def display_revision(tag: str) -> str:
name = tag.split("/", 1)[-1]
if name.startswith("rev-"):
return name[4:]
return name[1:] if re.match(r"v\d", name) else name
def history(slug: str) -> list[dict]:
fmt = "%(refname:short)%09%(creatordate:short)%09%(if)%(taggername)%(then)%(taggername)%(else)%(authorname)%(end)%09%(contents:subject)"
for scope in ([f"refs/tags/{slug}/v*", f"refs/tags/{slug}/rev-*"], ["refs/tags/v*", "refs/tags/rev-*"]):
out = git("for-each-ref", "--sort=creatordate", f"--format={fmt}", *scope)
rows = [line.split("\t") for line in (out or "").splitlines() if line.strip()]
if rows:
return [{"revision": display_revision(r[0]), "date": r[1], "author": r[2], "description": r[3][:160]}
for r in rows if len(r) == 4]
return []
def stamp(slug: str, release: bool = False) -> dict[str, str]:
dirty = bool(git("status", "--porcelain", "--", "documents", "assets", "captures", "brand"))
revision, exact, tag_date = None, False, None
patterns = _tag_patterns(slug)
for pattern in patterns:
tag = git("describe", "--tags", "--exact-match", "--match", pattern)
if tag:
revision, exact = display_revision(tag), True
# Issue date of a release = date of its tag (annotated tags can
# carry the real issue date), not of the last commit.
tag_date = git("for-each-ref", f"refs/tags/{tag}", "--format=%(creatordate:short)")
break
else:
for pattern in patterns:
described = git("describe", "--tags", "--match", pattern)
if described:
revision = display_revision(described)
break
if revision is None:
sha = git("rev-parse", "--short", "HEAD")
revision = f"0.0.0-{sha}" if sha else "unversioned"
if dirty:
revision += "+local"
date = (tag_date if exact and not dirty else None) or git("log", "-1", "--format=%cs") or dt.date.today().isoformat()
inputs = {
"revision": revision,
"date": date,
"draft": "false" if exact and not dirty else "true",
"history": json.dumps(history(slug), ensure_ascii=False),
}
if release:
inputs["release"] = "true"
return inputs
def font_args() -> list[str]:
for fonts in (ROOT / "brand" / "fonts", BRAND / "fonts"):
if fonts.is_dir():
# Only the bundled fonts (plus Typst's embedded math and mono
# fonts): every machine and CI runner renders the same glyphs.
return ["--font-path", str(fonts), "--ignore-system-fonts"]
return []
def typst_args(inputs: dict[str, str]) -> list[str]:
args = ["--root", str(ROOT), *font_args()]
for key, value in inputs.items():
args += ["--input", f"{key}={value}"]
return args
def compile_doc(doc: Doc, out_dir: Path, inputs: dict[str, str], fmt: str = "pdf", release: bool = False) -> bool:
suffix = "" if inputs["draft"] == "false" else "-draft"
if fmt == "pdf":
target = out_dir / f"{doc.output_stem}{suffix}.pdf"
else:
target = out_dir / f"{doc.output_stem}-{{p}}.{fmt}"
cmd = ["typst", "compile", *typst_args(inputs)]
if fmt == "png":
cmd += ["--format", "png", "--ppi", "110"]
if release:
cmd += ["--pdf-standard", "a-2b"]
cmd += [str(doc.path), str(target)]
res = subprocess.run(cmd, capture_output=True, text=True)
output = (res.stdout + res.stderr).strip()
if output:
print(output)
if res.returncode != 0:
print(f"FAILED {doc.ident}")
return False
if FONT_WARNING.search(output):
print(f"FAILED {doc.ident}: a font is missing (the brand fonts are in brand/fonts).")
return False
print(f"built {doc.ident:28} revision={inputs['revision']} draft={inputs['draft']} -> {target.relative_to(ROOT)}")
return True
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("documents", nargs="*", help="slug or slug:lang (default: all)")
parser.add_argument("--out", default="build", help="output folder (default: build)")
parser.add_argument("--png", action="store_true", help="render PNG pages instead of PDF")
parser.add_argument("--watch", action="store_true", help="recompile one document on every change")
parser.add_argument("--release", action="store_true", help="PDF/A; fail unless clean, tagged and TODO-free")
args = parser.parse_args()
if shutil.which("typst") is None:
sys.exit("typst is not on PATH. Install it: winget install --id Typst.Typst")
docs = find_documents(args.documents)
if not docs:
sys.exit("No documents found (expected documents/<name>/main.typ).")
out_dir = ROOT / args.out
out_dir.mkdir(parents=True, exist_ok=True)
if args.watch:
if len(docs) != 1:
sys.exit("--watch takes exactly one document, e.g. station-manual:fr")
doc = docs[0]
target = out_dir / f"{doc.output_stem}.pdf"
print(f"watching {doc.ident} -> {target.relative_to(ROOT)} (Ctrl+C to stop)")
return subprocess.call(["typst", "watch", *typst_args(stamp(doc.slug)), str(doc.path), str(target)])
lint = [sys.executable, str(TOOLS / "lint.py")] + (["--release"] if args.release else [])
if subprocess.run(lint + sorted({d.slug for d in docs}), cwd=ROOT).returncode != 0:
return 1
if (ROOT / "brand" / "MANIFEST.sha256").exists():
if subprocess.run([sys.executable, str(TOOLS / "brand.py"), "check"], cwd=ROOT).returncode != 0:
return 1
ok = True
stamps: dict[str, dict[str, str]] = {}
for doc in docs:
inputs = stamps.setdefault(doc.slug, stamp(doc.slug, release=args.release))
if args.release and inputs["draft"] != "false":
print(f"FAILED {doc.ident}: --release needs a clean tree and a tag on HEAD (got {inputs['revision']}).")
ok = False
continue
ok &= compile_doc(doc, out_dir, inputs, "png" if args.png else "pdf", release=args.release)
return 0 if ok else 1
if __name__ == "__main__":
sys.exit(main())
+405
View File
@@ -0,0 +1,405 @@
#!/usr/bin/env python3
"""Take the UI screenshots a software manual needs, from a manifest.
Run from the factory root:
python brand/tools/capture.py # every capture in captures.toml
python brand/tools/capture.py explore-advanced # one capture
python brand/tools/capture.py --list
Screenshots land in captures/<name>.png (root path /captures/<name>.png in
documents, used with #screenshot(...)). Commit them: documents must build
without the application running, and the PNG diff shows reviewers what
changed in the UI between two manual releases. Re-run before each release.
captures.toml:
[defaults]
base_url = "http://127.0.0.1:8765"
width = 1440 # CSS pixels
height = 900
scale = 2 # device pixel ratio; 2 keeps text sharp in print
wait_ms = 3000 # settle time after load and after each action
hide = [".dev-banner"] # CSS selectors hidden in every capture
[[capture]]
name = "explore-advanced"
path = "/" # or url = "https://..."
actions = [
{ click_text = "Advanced" }, # first link/button/tab with that text
{ click = "#toggle" }, # CSS selector
{ fill = ["#search", "Bridge"] },
{ wait_for = "#plot .main-svg" },
{ wait_ms = 500 },
{ eval = "window.scrollTo(0, 400)" },
]
selector = "#plot-area" # crop to one element
union = false # true: crop to all matches ("#toolbar > *")
full_page = false # capture the whole scrollable page
hide = ["#control-gallery"] # added to the defaults
The default engine drives a local Chrome or Edge through the DevTools
protocol and needs nothing else. Set engine = "playwright" (pip install
playwright; playwright install chromium) to use Playwright instead, and
CAPTURE_BROWSER to point at a browser executable.
Standard library only (Python 3.11+) unless Playwright is used.
"""
from __future__ import annotations
import argparse
import base64
import datetime as dt
import json
import os
import shutil
import socket
import struct
import subprocess
import sys
import tempfile
import time
import tomllib
import urllib.parse
import urllib.request
from pathlib import Path
ROOT = Path.cwd()
DEFAULTS = {"width": 1440, "height": 900, "scale": 2, "wait_ms": 3000, "engine": "cdp", "out_dir": "captures", "hide": []}
BROWSERS = [
r"C:\Program Files\Google\Chrome\Application\chrome.exe",
r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
r"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"google-chrome", "chromium", "chromium-browser", "microsoft-edge",
]
def load_manifest(path: Path) -> tuple[dict, list[dict]]:
data = tomllib.loads(path.read_text(encoding="utf-8"))
defaults = {**DEFAULTS, **data.get("defaults", {})}
caps = []
for cap in data.get("capture", []):
merged = {**defaults, **cap, "hide": list(defaults.get("hide", [])) + list(cap.get("hide", []))}
if "url" not in merged:
merged["url"] = merged.get("base_url", "").rstrip("/") + merged.get("path", "/")
caps.append(merged)
names = [c["name"] for c in caps]
if len(names) != len(set(names)):
sys.exit("captures.toml: capture names must be unique")
return defaults, caps
def find_browser() -> str | None:
if os.environ.get("CAPTURE_BROWSER"):
return os.environ["CAPTURE_BROWSER"]
for candidate in BROWSERS:
if os.path.isabs(candidate) and os.path.exists(candidate):
return candidate
found = shutil.which(candidate)
if found:
return found
return None
# ---------------------------------------------------------------------------
# Minimal Chrome DevTools Protocol client (WebSocket over a plain socket)
# ---------------------------------------------------------------------------
class DevTools:
def __init__(self, ws_url: str):
u = urllib.parse.urlparse(ws_url)
self.sock = socket.create_connection((u.hostname, u.port), timeout=90)
key = base64.b64encode(os.urandom(16)).decode()
self.sock.sendall(
f"GET {u.path} HTTP/1.1\r\nHost: {u.hostname}:{u.port}\r\nUpgrade: websocket\r\n"
f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n".encode()
)
head = b""
while b"\r\n\r\n" not in head:
chunk = self.sock.recv(4096)
if not chunk:
raise ConnectionError("DevTools handshake failed")
head += chunk
if b" 101 " not in head.split(b"\r\n", 1)[0]:
raise ConnectionError(head.split(b"\r\n", 1)[0].decode(errors="replace"))
self.buf = bytearray(head.split(b"\r\n\r\n", 1)[1])
self.next_id = 0
def _send_frame(self, opcode: int, data: bytes) -> None:
header = bytearray([0x80 | opcode])
n = len(data)
if n < 126:
header.append(0x80 | n)
elif n < 65536:
header.append(0x80 | 126)
header += struct.pack(">H", n)
else:
header.append(0x80 | 127)
header += struct.pack(">Q", n)
mask = os.urandom(4)
masked = bytes(b ^ mask[i % 4] for i, b in enumerate(data))
self.sock.sendall(bytes(header) + mask + masked)
def _read(self, n: int) -> bytes:
while len(self.buf) < n:
chunk = self.sock.recv(1 << 20)
if not chunk:
raise ConnectionError("DevTools connection closed")
self.buf += chunk
out = bytes(self.buf[:n])
del self.buf[:n]
return out
def _recv(self) -> dict:
message = bytearray()
while True:
b1, b2 = self._read(2)
opcode, n = b1 & 0x0F, b2 & 0x7F
if n == 126:
n = struct.unpack(">H", self._read(2))[0]
elif n == 127:
n = struct.unpack(">Q", self._read(8))[0]
mask = self._read(4) if b2 & 0x80 else None
payload = self._read(n)
if mask:
payload = bytes(b ^ mask[i % 4] for i, b in enumerate(payload))
if opcode == 9:
self._send_frame(10, payload)
continue
if opcode == 8:
raise ConnectionError("DevTools connection closed")
message += payload
if b1 & 0x80:
return json.loads(message)
def call(self, method: str, **params):
self.next_id += 1
self._send_frame(1, json.dumps({"id": self.next_id, "method": method, "params": params}).encode())
while True:
msg = self._recv()
if msg.get("id") == self.next_id:
if "error" in msg:
raise RuntimeError(f"{method}: {msg['error'].get('message')}")
return msg.get("result", {})
def js(self, expression: str):
res = self.call("Runtime.evaluate", expression=expression, returnByValue=True, awaitPromise=True)
if "exceptionDetails" in res:
raise RuntimeError(res["exceptionDetails"].get("exception", {}).get("description", expression))
return res.get("result", {}).get("value")
def _wait(page: DevTools, condition_js: str, timeout_s: float, what: str) -> None:
deadline = time.monotonic() + timeout_s
while time.monotonic() < deadline:
if page.js(condition_js):
return
time.sleep(0.1)
raise RuntimeError(f"timed out waiting for {what}")
CLICK_TEXT_JS = """(() => {
const want = %s;
const nodes = [...document.querySelectorAll('a, button, [role=tab], [role=button], label, summary, .nav-link')];
const el = nodes.find(n => n.textContent.trim() === want) || nodes.find(n => n.textContent.trim().includes(want));
if (!el) return false;
el.scrollIntoView({block: 'center'}); el.click(); return true;
})()"""
# Bounding box (document coordinates) of the first match, or of all matches
# with union = true (e.g. "#toolbar > *" to crop a row to its controls).
BOX_JS = """((sel, union, scroll) => {
const els = union ? [...document.querySelectorAll(sel)] : [document.querySelector(sel)].filter(Boolean);
if (!els.length) return null;
if (scroll) els[0].scrollIntoView({block: 'center'});
const rs = els.map(e => e.getBoundingClientRect()).filter(r => r.width && r.height);
if (!rs.length) return null;
const l = Math.min(...rs.map(r => r.left)), t = Math.min(...rs.map(r => r.top));
const r = Math.max(...rs.map(r => r.right)), b = Math.max(...rs.map(r => r.bottom));
return {x: l + window.scrollX, y: t + window.scrollY, width: r - l, height: b - t};
})(%s, %s, %s)"""
FILL_JS = """(() => {
const el = document.querySelector(%s);
if (!el) return false;
const setter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el), 'value').set;
setter.call(el, %s);
el.dispatchEvent(new Event('input', {bubbles: true}));
el.dispatchEvent(new Event('change', {bubbles: true}));
return true;
})()"""
def capture_cdp(browser: str, caps: list[dict], outputs: list[Path]) -> int:
failed = 0
# Windows may still hold profile files for a moment after the browser exits.
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as profile:
proc = subprocess.Popen(
[browser, "--headless=new", "--disable-gpu", "--hide-scrollbars", "--no-first-run",
"--no-default-browser-check", "--remote-debugging-port=0", f"--user-data-dir={profile}", "about:blank"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
try:
port_file = Path(profile) / "DevToolsActivePort"
deadline = time.monotonic() + 30
while not port_file.exists() or not port_file.read_text().strip():
if time.monotonic() > deadline:
raise RuntimeError("browser did not open its DevTools port")
time.sleep(0.1)
port = int(port_file.read_text().splitlines()[0])
targets = json.load(urllib.request.urlopen(f"http://127.0.0.1:{port}/json/list"))
page = DevTools(next(t for t in targets if t["type"] == "page")["webSocketDebuggerUrl"])
page.call("Page.enable")
page.call("Runtime.enable")
for cap, out in zip(caps, outputs):
try:
shoot(page, cap, out)
print(f"captured {cap['name']} <- {cap['url']}")
except Exception as exc: # report every capture, fail at the end
failed += 1
print(f"FAILED {cap['name']}: {exc}")
finally:
proc.terminate()
try:
proc.wait(timeout=10)
except subprocess.TimeoutExpired:
proc.kill()
return failed
def shoot(page: DevTools, cap: dict, out: Path) -> None:
width, height, scale, wait_ms = cap["width"], cap["height"], cap["scale"], cap["wait_ms"]
# Device scale 1 and the resolution from the clip scale, so clip
# coordinates are plain CSS pixels.
page.call("Emulation.setDeviceMetricsOverride", width=width, height=height, deviceScaleFactor=1, mobile=False)
page.call("Page.navigate", url=cap["url"])
time.sleep(0.2)
_wait(page, "document.readyState === 'complete'", 60, "page load")
if cap.get("hide"):
css = ", ".join(cap["hide"]) + " { display: none !important; }"
page.js(f"(() => {{ const s = document.createElement('style'); s.textContent = {json.dumps(css)}; document.head.appendChild(s); return true; }})()")
time.sleep(wait_ms / 1000)
for action in cap.get("actions", []):
if "click" in action:
if not page.js(f"(() => {{ const el = document.querySelector({json.dumps(action['click'])}); if (!el) return false; el.scrollIntoView({{block: 'center'}}); el.click(); return true; }})()"):
raise RuntimeError(f"nothing matches {action['click']!r}")
elif "click_text" in action:
if not page.js(CLICK_TEXT_JS % json.dumps(action["click_text"])):
raise RuntimeError(f"no clickable element with text {action['click_text']!r}")
elif "fill" in action:
sel, value = action["fill"]
if not page.js(FILL_JS % (json.dumps(sel), json.dumps(value))):
raise RuntimeError(f"nothing matches {sel!r}")
elif "wait_for" in action:
_wait(page, f"!!document.querySelector({json.dumps(action['wait_for'])})", 30, action["wait_for"])
elif "eval" in action:
page.js(action["eval"])
# Settle after each action: its own wait_ms, else the capture's.
time.sleep(action.get("wait_ms", wait_ms) / 1000)
params = {"format": "png", "captureBeyondViewport": bool(cap.get("full_page"))}
if cap.get("selector"):
# Scroll the element into view and clip in document coordinates
# (viewport rectangle + scroll offsets). Elements taller than the
# viewport get a taller viewport.
args = (json.dumps(cap["selector"]), json.dumps(bool(cap.get("union"))))
size = page.js(BOX_JS % (*args, "false"))
if not size or not size["width"] or not size["height"]:
raise RuntimeError(f"selector {cap['selector']!r} not found or empty")
if size["height"] > height:
page.call("Emulation.setDeviceMetricsOverride", width=width, height=int(size["height"]) + 40, deviceScaleFactor=1, mobile=False)
time.sleep(0.5)
rect = page.js(BOX_JS % (*args, "true"))
time.sleep(0.3)
# Chrome drops a clip with a negative origin (Bootstrap rows have a
# -4px gutter) and silently captures from (0, 0): clamp to the page.
x0, y0 = max(0.0, rect["x"]), max(0.0, rect["y"])
x1 = min(rect["x"] + rect["width"], float(page.js("document.documentElement.scrollWidth")))
y1 = rect["y"] + rect["height"]
params["clip"] = {"x": x0, "y": y0, "width": x1 - x0, "height": y1 - y0, "scale": scale}
elif cap.get("full_page"):
size = page.call("Page.getLayoutMetrics")["cssContentSize"]
params["clip"] = {"x": 0, "y": 0, "width": size["width"], "height": size["height"], "scale": scale}
else:
params["clip"] = {"x": 0, "y": 0, "width": width, "height": height, "scale": scale}
data = page.call("Page.captureScreenshot", **params)["data"]
out.write_bytes(base64.b64decode(data))
def capture_playwright(caps: list[dict], outputs: list[Path]) -> int:
from playwright.sync_api import sync_playwright # noqa: PLC0415
with sync_playwright() as pw:
browser = pw.chromium.launch()
for cap, out in zip(caps, outputs):
page = browser.new_page(viewport={"width": cap["width"], "height": cap["height"]}, device_scale_factor=cap["scale"])
page.goto(cap["url"], wait_until="networkidle")
if cap.get("hide"):
page.add_style_tag(content=", ".join(cap["hide"]) + " { display: none !important; }")
page.wait_for_timeout(cap["wait_ms"])
for action in cap.get("actions", []):
if "click" in action:
page.click(action["click"])
elif "click_text" in action:
page.get_by_text(action["click_text"], exact=True).first.click()
elif "fill" in action:
page.fill(*action["fill"])
elif "wait_for" in action:
page.wait_for_selector(action["wait_for"])
elif "eval" in action:
page.evaluate(action["eval"])
page.wait_for_timeout(action.get("wait_ms", cap["wait_ms"]))
if cap.get("selector"):
page.locator(cap["selector"]).first.screenshot(path=str(out))
else:
page.screenshot(path=str(out), full_page=bool(cap.get("full_page")))
page.close()
print(f"captured {cap['name']} <- {cap['url']}")
browser.close()
return 0
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("names", nargs="*")
ap.add_argument("--manifest", default="captures.toml")
ap.add_argument("--list", action="store_true")
args = ap.parse_args()
manifest = ROOT / args.manifest
if not manifest.exists():
sys.exit(f"{manifest} not found")
defaults, caps = load_manifest(manifest)
if args.list:
for c in caps:
print(f"{c['name']:30} {c['url']}")
return 0
if args.names:
caps = [c for c in caps if c["name"] in set(args.names)]
if not caps:
sys.exit("no matching capture")
out_dir = ROOT / defaults["out_dir"]
out_dir.mkdir(parents=True, exist_ok=True)
outputs = [out_dir / f"{c['name']}.png" for c in caps]
if defaults["engine"] == "playwright":
failed = capture_playwright(caps, outputs)
else:
browser = find_browser()
if not browser:
sys.exit("No Chrome or Edge found; set CAPTURE_BROWSER")
failed = capture_cdp(browser, caps, outputs)
index_path = out_dir / "captures.json"
index = json.loads(index_path.read_text(encoding="utf-8")) if index_path.exists() else {}
stamp = dt.datetime.now().astimezone().isoformat(timespec="seconds")
for cap, out in zip(caps, outputs):
if out.exists() and out.stat().st_mtime > time.time() - 600:
index[cap["name"]] = {"url": cap["url"], "captured": stamp, "viewport": [cap["width"], cap["height"]], "scale": cap["scale"]}
index_path.write_text(json.dumps(dict(sorted(index.items())), indent=2) + "\n", encoding="utf-8", newline="\n")
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env bash
# Install Typst (and git/python) in a Debian/Ubuntu CI container. The brand
# fonts are bundled in fonts/ (brand/fonts in a factory), so nothing else is
# needed. Used by the brand and factory workflows. Keep TYPST_VERSION in step
# with the version the brand is tested with (README.md).
set -euo pipefail
TYPST_VERSION="${TYPST_VERSION:-0.14.2}"
if command -v apt-get >/dev/null; then
apt-get update -qq
apt-get install -y -qq curl xz-utils git ca-certificates python3 >/dev/null
fi
curl -fsSL "https://github.com/typst/typst/releases/download/v${TYPST_VERSION}/typst-x86_64-unknown-linux-musl.tar.xz" \
| tar -xJ --strip-components=1 -C /usr/local/bin typst-x86_64-unknown-linux-musl/typst
typst --version
+756
View File
@@ -0,0 +1,756 @@
#!/usr/bin/env python3
"""Convert a Word document (.docx) into a draft AIMsight technical document.
Run from the factory root:
python brand/tools/docx2typ.py "imports/CAM quick start guide.docx" cam-quick-start
python brand/tools/docx2typ.py old.docx user-manual --lang fr --density standard
Writes documents/<slug>/main.typ and extracts pictures to
documents/<slug>/images/. The output uses only the public brand API
(headings, lists, tables, #fig, callouts, #footnote) so it passes
`tools/lint.py`; all page furniture comes from the template.
What is converted: title/subtitle, headings (Heading n / Titre n / outline
level), paragraphs with bold/italic/super/subscript, hyperlinks, bullet and
numbered lists (nested), tables (header row, column spans), pictures with
their Caption paragraph, text boxes, footnotes, "Note:/Warning:/..."
paragraphs as callouts.
What is dropped, with a review list at the top of main.typ: headers/footers,
Word fields such as the table of contents, comments, tracked deletions,
EMF/WMF pictures (replaced by #placeholder-figure). Read the draft, fix the
review items, then delete the review comment block.
Standard library only (Python 3.11+).
"""
from __future__ import annotations
import argparse
import datetime as dt
import re
import sys
import zipfile
from dataclasses import dataclass, field
from pathlib import Path, PurePosixPath
from xml.etree import ElementTree as ET
NS = {
"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
"r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
"a": "http://schemas.openxmlformats.org/drawingml/2006/main",
"wp": "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",
"mc": "http://schemas.openxmlformats.org/markup-compatibility/2006",
"v": "urn:schemas-microsoft-com:vml",
"rel": "http://schemas.openxmlformats.org/package/2006/relationships",
"dc": "http://purl.org/dc/elements/1.1/",
"cp": "http://schemas.openxmlformats.org/package/2006/metadata/core-properties",
}
def q(tag: str) -> str:
prefix, local = tag.split(":")
return f"{{{NS[prefix]}}}{local}"
W = lambda local: q("w:" + local) # noqa: E731
EMU_PER_INCH = 914400
TEXT_WIDTH_IN = 162 / 25.4 # A4 technical template text width
SUPPORTED_IMAGES = {".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp"}
CALLOUTS = [
(re.compile(r"^(danger|gefahr|pericolo)\s*[:!-]\s*", re.I), "danger"),
(re.compile(r"^(warning|avertissement|warnung|avvertenza)\s*[:!-]\s*", re.I), "warning"),
(re.compile(r"^(caution|attention|vorsicht|attenzione|important)\s*[:!-]\s*", re.I), "caution"),
(re.compile(r"^(tip|hint|conseil|astuce|tipp)\s*[:!-]\s*", re.I), "tip"),
(re.compile(r"^(note|nb|n\.b\.|remarque|hinweis|nota)\s*[:!-]\s*", re.I), "note"),
]
# ---------------------------------------------------------------------------
# Typst escaping
# ---------------------------------------------------------------------------
_ESCAPE = re.compile(r"([\\#*_`$<>@\[\]~])")
def esc(text: str) -> str:
text = _ESCAPE.sub(r"\\\1", text)
# "//" and "/*" would start comments (URLs keep working because Typst
# recognises them before comments).
text = re.sub(r"(?<!:)/(?=[/*])", r"\\/", text)
return text
def esc_line_start(text: str) -> str:
# Markup that is only special at the start of a line.
return re.sub(r"^(\s*)([-+=/])(?=\s|$)", r"\1\\\2", text)
# ---------------------------------------------------------------------------
# Package parts
# ---------------------------------------------------------------------------
@dataclass
class Package:
zf: zipfile.ZipFile
rels: dict[str, str]
link_rels: dict[str, str]
styles: dict[str, dict]
numbering: dict[tuple[str, int], str]
footnotes: dict[str, ET.Element]
lang: str | None
core: dict[str, str]
@classmethod
def open(cls, path: Path) -> "Package":
zf = zipfile.ZipFile(path)
names = set(zf.namelist())
def xml(name):
return ET.fromstring(zf.read(name)) if name in names else None
rels, link_rels = {}, {}
rel_root = xml("word/_rels/document.xml.rels")
if rel_root is not None:
for rel in rel_root.findall("rel:Relationship", NS):
target = rel.get("Target", "")
if rel.get("TargetMode") == "External":
link_rels[rel.get("Id")] = target
else:
rels[rel.get("Id")] = str(PurePosixPath("word") / target) if not target.startswith("/") else target[1:]
styles, lang = {}, None
st = xml("word/styles.xml")
if st is not None:
for s in st.findall("w:style", NS):
sid = s.get(W("styleId"))
name_el = s.find("w:name", NS)
outline = s.find("w:pPr/w:outlineLvl", NS)
based = s.find("w:basedOn", NS)
link = s.find("w:link", NS)
styles[sid] = {
"link": link.get(W("val")) if link is not None else None,
"name": (name_el.get(W("val")) if name_el is not None else sid or "").lower(),
"outline": int(outline.get(W("val"))) if outline is not None else None,
"based": based.get(W("val")) if based is not None else None,
}
lang_el = st.find("w:docDefaults/w:rPrDefault/w:rPr/w:lang", NS)
if lang_el is not None and lang_el.get(W("val")):
lang = lang_el.get(W("val")).split("-")[0].lower()
numbering = {}
nb = xml("word/numbering.xml")
if nb is not None:
abstract = {}
for an in nb.findall("w:abstractNum", NS):
levels = {}
for lvl in an.findall("w:lvl", NS):
fmt = lvl.find("w:numFmt", NS)
levels[int(lvl.get(W("ilvl")))] = fmt.get(W("val")) if fmt is not None else "bullet"
abstract[an.get(W("abstractNumId"))] = levels
for num in nb.findall("w:num", NS):
ref = num.find("w:abstractNumId", NS)
levels = abstract.get(ref.get(W("val")) if ref is not None else None, {})
for ilvl, fmt in levels.items():
numbering[(num.get(W("numId")), ilvl)] = fmt
footnotes = {}
fn = xml("word/footnotes.xml")
if fn is not None:
for f in fn.findall("w:footnote", NS):
footnotes[f.get(W("id"))] = f
core = {}
cr = xml("docProps/core.xml")
if cr is not None:
for key, tag in (("title", "dc:title"), ("creator", "dc:creator"), ("subject", "dc:subject")):
el = cr.find(tag, NS)
if el is not None and el.text:
core[key] = el.text.strip()
return cls(zf, rels, link_rels, styles, numbering, footnotes, lang, core)
def style_info(self, style_id: str | None) -> tuple[str, int | None]:
"""Return (role, level): role in title/subtitle/heading/caption/list/body."""
seen = set()
sid = style_id
while sid and sid not in seen:
seen.add(sid)
info = self.styles.get(sid, {"name": sid.lower(), "outline": None, "based": None})
name = info["name"]
if name in ("title", "titre"):
return "title", None
if name in ("subtitle", "sous-titre"):
return "subtitle", None
m = re.match(r"(heading|titre|überschrift|titolo)\s*(\d)", name)
if m:
return "heading", int(m.group(2))
if info["outline"] is not None and info["outline"] < 9:
return "heading", info["outline"] + 1
if name in ("caption", "légende", "beschriftung", "didascalia"):
return "caption", None
sid = info["based"]
return "body", None
# ---------------------------------------------------------------------------
# Inline content
# ---------------------------------------------------------------------------
@dataclass
class Run:
text: str
bold: bool = False
italic: bool = False
vert: str | None = None
link: str | None = None
raw: bool = False # already Typst markup (footnotes, line breaks)
cstyle: str | None = None # character style id
@dataclass
class Block:
kind: str # para, heading, image, list, table, caption, textbox
text: str = ""
level: int = 0
data: dict = field(default_factory=dict)
def on(rpr: ET.Element | None, tag: str) -> bool:
if rpr is None:
return False
el = rpr.find(f"w:{tag}", NS)
return el is not None and el.get(W("val"), "true") not in ("0", "false", "none")
class Converter:
def __init__(self, pkg: Package, slug: str, images_dir: Path, review: list[str]):
self.pkg = pkg
self.slug = slug
self.images_dir = images_dir
self.review = review
self.image_count = 0
self.dropped_fields: set[str] = set()
self.dropped_labels = 0
self.promoted: list[str] = []
self.last_heading = 1
# -- pictures ----------------------------------------------------------
def extract_image(self, rid: str, cx_emu: int | None) -> Block:
part = self.pkg.rels.get(rid)
if not part or part not in self.pkg.zf.namelist():
self.review.append(f"picture {rid} not found in the package")
return Block("placeholder", data={"note": "Picture missing from the Word file"})
ext = PurePosixPath(part).suffix.lower()
self.image_count += 1
name = f"figure-{self.image_count:02d}{'.jpg' if ext == '.jpeg' else ext}"
width_in = (cx_emu or 0) / EMU_PER_INCH
if ext not in SUPPORTED_IMAGES:
self.review.append(f"{name}: {ext} pictures are not supported by Typst; export it as PNG/SVG")
return Block("placeholder", data={"note": f"Replace {PurePosixPath(part).name} ({ext[1:].upper()})"})
self.images_dir.mkdir(parents=True, exist_ok=True)
data = self.pkg.zf.read(part)
(self.images_dir / name).write_bytes(data)
aspect = None
if data[:8] == b"\x89PNG\r\n\x1a\n":
w, h = int.from_bytes(data[16:20], "big"), int.from_bytes(data[20:24], "big")
aspect = w / h if h else None
return Block("image", data={"path": f"/documents/{self.slug}/images/{name}", "width_in": width_in, "aspect": aspect})
def drawing(self, el: ET.Element, out_blocks: list[Block], runs: list[Run]) -> None:
extent = el.find(".//wp:extent", NS)
cx = int(extent.get("cx")) if extent is not None else None
for blip in el.iter(q("a:blip")):
rid = blip.get(q("r:embed")) or blip.get(q("r:link"))
if rid:
block = self.extract_image(rid, cx)
width_in = block.data.get("width_in", 0)
if block.kind == "image" and 0 < width_in <= 0.6:
# Icon-sized picture inside a sentence. The box needs an
# explicit width: the template centres every image, which
# would otherwise stretch the box to the full line.
aspect = block.data.get("aspect") or 1.0
runs.append(Run(
f'#box(width: {aspect:.2f}em, baseline: 15%, image("{block.data["path"]}", height: 1em))',
raw=True,
))
else:
out_blocks.append(block)
for tb in el.iter(W("txbxContent")):
self.textbox(tb, out_blocks)
def textbox(self, tb: ET.Element, out_blocks: list[Block]) -> None:
texts = []
for p in tb.findall("w:p", NS):
inner_blocks: list[Block] = []
line = self.render_runs(self.collect_runs(p, inner_blocks))
if line.strip():
texts.append(line.strip())
out_blocks.extend(inner_blocks)
joined = "\n\n".join(texts)
if len(re.sub(r"\W", "", joined)) <= 3:
# Callout numbers ("1.", "A") drawn over a picture.
self.dropped_labels += 1
elif texts:
out_blocks.append(Block("textbox", text=joined))
# -- runs ----------------------------------------------------------------
def collect_runs(self, p: ET.Element, out_blocks: list[Block]) -> list[Run]:
runs: list[Run] = []
field_depth = 0
field_state: list[str] = [] # per nesting level: "instr" | "result" | "skip"
instr: list[str] = []
def walk(node: ET.Element, link: str | None = None):
nonlocal field_depth
for child in node:
tag = child.tag
if tag == q("mc:AlternateContent"):
choice = child.find("mc:Choice", NS)
if choice is not None:
walk(choice, link)
elif tag == W("hyperlink"):
rid = child.get(q("r:id"))
url = self.pkg.link_rels.get(rid) if rid else None
walk(child, url or link)
elif tag in (W("ins"), W("smartTag"), W("fldSimple"), W("customXml")):
walk(child, link)
elif tag == W("sdt"):
content = child.find("w:sdtContent", NS)
if content is not None:
walk(content, link)
elif tag == W("del"):
continue
elif tag == W("r"):
rpr = child.find("w:rPr", NS)
fld = child.find("w:fldChar", NS)
if fld is not None:
kind = fld.get(W("fldCharType"))
if kind == "begin":
field_state.append("instr")
instr.clear()
elif kind == "separate" and field_state:
code = "".join(instr).strip().split(" ")[0].upper()
keep = code in ("HYPERLINK", "REF", "PAGEREF", "SEQ", "")
if not keep:
self.dropped_fields.add(code)
field_state[-1] = "result" if keep and code != "PAGEREF" else "skip"
elif kind == "end" and field_state:
field_state.pop()
continue
if field_state and field_state[-1] == "instr":
for it in child.findall("w:instrText", NS):
instr.append(it.text or "")
continue
if field_state and field_state[-1] == "skip":
continue
bold, italic = on(rpr, "b"), on(rpr, "i")
rstyle = rpr.find("w:rStyle", NS) if rpr is not None else None
cstyle = rstyle.get(W("val")) if rstyle is not None else None
va = rpr.find("w:vertAlign", NS) if rpr is not None else None
vert = va.get(W("val")) if va is not None and va.get(W("val")) in ("superscript", "subscript") else None
for part in child:
if part.tag == W("t"):
runs.append(Run(part.text or "", bold, italic, vert, link, cstyle=cstyle))
elif part.tag == W("tab"):
runs.append(Run(" ", bold, italic, vert, link))
elif part.tag == W("br"):
if part.get(W("type")) not in ("page", "column"):
runs.append(Run(" \\\n", raw=True))
elif part.tag == W("noBreakHyphen"):
runs.append(Run("‑", bold, italic, vert, link))
elif part.tag == W("sym"):
runs.append(Run("•", bold, italic, vert, link))
elif part.tag == W("footnoteReference"):
runs.append(Run(self.footnote(part.get(W("id"))), raw=True))
elif part.tag == W("drawing"):
self.drawing(part, out_blocks, runs)
elif part.tag == q("mc:AlternateContent"):
choice = part.find("mc:Choice", NS)
if choice is not None:
for d in choice.iter(W("drawing")):
self.drawing(d, out_blocks, runs)
elif part.tag == W("pict"):
self.pict(part, out_blocks)
elif tag == W("pict"):
self.pict(child, out_blocks)
walk(p)
return runs
def pict(self, el: ET.Element, out_blocks: list[Block]) -> None:
# Legacy VML. Only reached when there is no DrawingML alternative.
for img in el.iter(q("v:imagedata")):
rid = img.get(q("r:id"))
if rid:
out_blocks.append(self.extract_image(rid, None))
for tb in el.iter(W("txbxContent")):
self.textbox(tb, out_blocks)
def footnote(self, fid: str | None) -> str:
note = self.pkg.footnotes.get(fid or "")
if note is None:
return ""
parts = []
for p in note.findall("w:p", NS):
parts.append(self.render_runs(self.collect_runs(p, [])).strip())
return "#footnote[" + " ".join(x for x in parts if x) + "]"
@staticmethod
def render_runs(runs: list[Run]) -> str:
# Merge neighbours with identical formatting so markup stays readable.
merged: list[Run] = []
for r in runs:
if merged and not r.raw and not merged[-1].raw and (
merged[-1].bold, merged[-1].italic, merged[-1].vert, merged[-1].link
) == (r.bold, r.italic, r.vert, r.link):
merged[-1].text += r.text
else:
merged.append(Run(r.text, r.bold, r.italic, r.vert, r.link, r.raw))
out = []
for r in merged:
if r.raw:
out.append(r.text)
continue
text = r.text
if not text:
continue
lead = text[: len(text) - len(text.lstrip())]
trail = text[len(text.rstrip()):]
core = text.strip()
if not core:
out.append(text)
continue
s = esc(core)
if r.vert == "superscript":
s = f"#super[{s}]"
elif r.vert == "subscript":
s = f"#sub[{s}]"
if r.italic:
s = f"#emph[{s}]"
if r.bold:
s = f"#strong[{s}]"
if r.link:
s = f'#link("{r.link}")[{s}]'
out.append(lead + s + trail)
return re.sub(r"[ \t]+", " ", "".join(out))
# -- block level ---------------------------------------------------------
def paragraph(self, p: ET.Element, in_table: bool = False) -> list[Block]:
ppr = p.find("w:pPr", NS)
style = ppr.find("w:pStyle", NS) if ppr is not None else None
role, level = self.pkg.style_info(style.get(W("val")) if style is not None else None)
outline = ppr.find("w:outlineLvl", NS) if ppr is not None else None
if role == "body" and outline is not None and int(outline.get(W("val"))) < 9:
role, level = "heading", int(outline.get(W("val"))) + 1
num = ppr.find("w:numPr", NS) if ppr is not None else None
extra: list[Block] = []
runs = self.collect_runs(p, extra)
text = self.render_runs(runs).strip()
blocks: list[Block] = []
if role == "body" and num is None and text and not in_table:
pseudo = self.pseudo_heading(runs)
if pseudo:
role, level = "heading", pseudo
self.promoted.append(re.sub(r"#\w+\[(.*?)\]", r"\1", text))
if role == "heading":
self.last_heading = level or 1
if text:
if role in ("title", "subtitle", "heading", "caption"):
# Headings are plain text: bold/italic markup inside them is noise.
plain = re.sub(r"#(strong|emph)\[(.*?)\]", r"\2", text).rstrip(":").strip()
blocks.append(Block(role, text=plain, level=level or 1))
elif num is not None and role == "body":
ilvl_el, numid_el = num.find("w:ilvl", NS), num.find("w:numId", NS)
ilvl = int(ilvl_el.get(W("val"))) if ilvl_el is not None else 0
numid = numid_el.get(W("val")) if numid_el is not None else "0"
if numid == "0":
blocks.append(Block("para", text=text))
else:
fmt = self.pkg.numbering.get((numid, ilvl), "bullet")
blocks.append(Block("list", text=text, level=ilvl, data={"ordered": fmt not in ("bullet", "none"), "num_id": numid}))
else:
blocks.append(Block("para", text=text))
return blocks + extra
def pseudo_heading(self, runs: list[Run]) -> int | None:
"""Heading level for a body paragraph that only looks like a heading."""
texty = [r for r in runs if not r.raw and r.text.strip()]
if not texty:
return None
styles = {r.cstyle for r in texty}
if len(styles) == 1 and None not in styles:
sid = styles.pop()
linked = self.pkg.styles.get(sid, {}).get("link")
role, level = self.pkg.style_info(linked) if linked else ("body", None)
if role == "heading":
return level
m = re.match(r"heading(\d)char", sid.lower())
if m:
return int(m.group(1))
plain = "".join(r.text for r in texty).strip()
if all(r.bold for r in texty) and len(plain.split()) <= 8 and not re.search(r"[.;,]$", plain):
return min(self.last_heading + 1, 3)
return None
def table(self, tbl: ET.Element) -> Block:
rows = []
header_rows = 0
for i, tr in enumerate(tbl.findall("w:tr", NS)):
trpr = tr.find("w:trPr", NS)
if trpr is not None and trpr.find("w:tblHeader", NS) is not None and i == header_rows:
header_rows += 1
cells = []
for tc in tr.findall("w:tc", NS):
tcpr = tc.find("w:tcPr", NS)
span = tcpr.find("w:gridSpan", NS) if tcpr is not None else None
vmerge = tcpr.find("w:vMerge", NS) if tcpr is not None else None
parts, nested = [], []
for child in tc:
if child.tag == W("p"):
for b in self.paragraph(child, in_table=True):
if b.kind == "list":
parts.append("- " + b.text)
elif b.kind in ("para", "heading", "caption", "title", "subtitle"):
parts.append(b.text)
elif b.kind == "image":
parts.append(f'#image("{b.data["path"]}")')
else:
nested.append(b)
elif child.tag == W("tbl"):
self.review.append("nested table flattened into its parent cell")
nested.append(self.table(child))
cells.append({
"text": " \\\n".join(parts),
"span": int(span.get(W("val"))) if span is not None else 1,
"continued": vmerge is not None and vmerge.get(W("val")) != "restart",
})
rows.append(cells)
if not header_rows and rows and all(c["text"].startswith("#strong[") or not c["text"] for c in rows[0]):
header_rows = 1
ncols = max((sum(c["span"] for c in r) for r in rows), default=1)
if any(c["continued"] for r in rows for c in r):
self.review.append("table with vertically merged cells: check the rows after conversion")
return Block("table", data={"rows": rows, "header": header_rows, "columns": ncols})
def body_blocks(self, body: ET.Element) -> list[Block]:
blocks: list[Block] = []
for child in body:
if child.tag == W("p"):
blocks += self.paragraph(child)
elif child.tag == W("tbl"):
blocks.append(self.table(child))
elif child.tag == W("sdt"):
gallery = child.find(".//w:docPartGallery", NS)
if gallery is not None and "contents" in (gallery.get(W("val")) or "").lower():
self.dropped_fields.add("TOC")
continue
content = child.find("w:sdtContent", NS)
if content is not None:
blocks += self.body_blocks(content)
return blocks
# ---------------------------------------------------------------------------
# Typst emission
# ---------------------------------------------------------------------------
def callout(text: str) -> tuple[str | None, str]:
plain = re.sub(r"^#strong\[(.*?)\]\s*", r"\1 ", text)
for rx, kind in CALLOUTS:
if rx.match(plain):
body = rx.sub("", plain, count=1).strip()
return kind, body[:1].upper() + body[1:]
return None, text
def figure_line(block: Block, caption: str | None) -> str:
if block.kind == "placeholder":
cap = f"[{caption}]" if caption else "[Figure]"
return f'#placeholder-figure({cap}, note: [{esc(block.data["note"])}])'
width_in = block.data.get("width_in") or TEXT_WIDTH_IN
pct = max(10, min(100, round(width_in / TEXT_WIDTH_IN * 100 / 5) * 5))
args = [f'"{block.data["path"]}"']
if pct < 100:
args.append(f"width: {pct}%")
if caption:
args.append(f"caption: [{caption}]")
return f"#fig({', '.join(args)})"
def emit(blocks: list[Block]) -> tuple[str, dict]:
meta: dict[str, str] = {}
out: list[str] = []
counters: dict[tuple, int] = {}
# No Title paragraph: the first heading, when nothing precedes it, is the
# document title (otherwise it repeats as chapter 1 under the title).
if not any(b.kind == "title" for b in blocks):
first = next((k for k, b in enumerate(blocks) if b.kind not in ("textbox",)), None)
if first is not None and blocks[first].kind == "heading":
blocks = blocks[:first] + [Block("title", text=blocks[first].text)] + blocks[first + 1:]
i = 0
prev_kind = None
last_level = 0
while i < len(blocks):
b = blocks[i]
if b.kind == "title" and "title" not in meta:
meta["title"] = b.text
elif b.kind == "subtitle" and "subtitle" not in meta:
meta["subtitle"] = b.text
elif b.kind == "heading":
# Word allows Heading 2 -> Heading 4; numbered headings would then
# read 1.2.0.1. Never go more than one level deeper.
level = max(1, min(b.level, 4, last_level + 1))
last_level = level
out.append("")
out.append("=" * level + " " + b.text)
elif b.kind in ("image", "placeholder"):
caption = None
if i + 1 < len(blocks) and blocks[i + 1].kind == "caption":
caption = blocks[i + 1].text
i += 1
elif i > 0 and blocks[i - 1].kind == "caption" and prev_kind != "figure":
caption = blocks[i - 1].text
out.append("")
out.append(figure_line(b, caption))
prev_kind = "figure"
i += 1
continue
elif b.kind == "caption":
# A caption directly before a picture is consumed by that picture.
if not (i + 1 < len(blocks) and blocks[i + 1].kind in ("image", "placeholder")):
out.append("")
out.append(f"// Caption without picture: {b.text}")
elif b.kind == "list":
if prev_kind != "list":
out.append("")
key = (b.data.get("num_id"), b.level)
for k in [k for k in counters if k[0] == key[0] and k[1] > b.level]:
del counters[k]
if b.data.get("ordered"):
# Explicit numbers: Word keeps counting across pictures that
# interrupt a list, a Typst `+` list would restart at 1.
counters[key] = counters.get(key, 0) + 1
marker = f"{counters[key]}."
else:
marker = "-"
out.append(" " * b.level + f"{marker} {b.text}")
elif b.kind == "textbox":
out.append("")
out.append(f"#note[{b.text}] // from a Word text box: check placement")
elif b.kind == "table":
out.append("")
out += table_lines(b)
elif b.kind == "para":
kind, body = callout(b.text)
out.append("")
out.append(f"#{kind}[{body}]" if kind else esc_line_start(b.text))
prev_kind = b.kind
i += 1
return "\n".join(out).strip() + "\n", meta
def table_lines(b: Block) -> list[str]:
rows, header, ncols = b.data["rows"], b.data["header"], b.data["columns"]
def cell(c):
text = c["text"] or ""
if c["continued"]:
text = ""
if c["span"] > 1:
return f"table.cell(colspan: {c['span']})[{text}]"
return f"[{text}]"
if header == 1 and all(c["span"] == 1 for c in rows[0]):
# One header row: the brand's data-table shades and repeats it.
names = ", ".join("[" + re.sub(r"^#strong\[(.*)\]$", r"\1", c["text"] or "") + "]" for c in rows[0])
lines = ["#data-table(", f" columns: {ncols},", f" header: ({names},),"]
lines += [f" {', '.join(cell(c) for c in row)}," for row in rows[1:]]
return lines + [")"]
lines = ["#table(", f" columns: {ncols},"]
for r_i, row in enumerate(rows):
cells = ", ".join(cell(c) for c in row)
if r_i < header:
lines.append(f" table.header({cells}),")
else:
lines.append(f" {cells},")
lines.append(")")
return lines
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("docx", type=Path)
ap.add_argument("slug", help="document folder name, e.g. cam-quick-start")
ap.add_argument("--lang", help="document language (default: from the Word file)")
ap.add_argument("--density", default="compact", choices=["compact", "standard"])
ap.add_argument("--label", help="running-header label (default: title in capitals)")
ap.add_argument("--force", action="store_true", help="overwrite an existing main.typ")
args = ap.parse_args()
if not re.fullmatch(r"[a-z0-9][a-z0-9-]*", args.slug):
sys.exit("slug must be lowercase letters, digits and dashes")
doc_dir = Path.cwd() / "documents" / args.slug
target = doc_dir / "main.typ"
if target.exists() and not args.force:
sys.exit(f"{target} exists; use --force to overwrite")
pkg = Package.open(args.docx)
review: list[str] = []
conv = Converter(pkg, args.slug, doc_dir / "images", review)
root = ET.fromstring(pkg.zf.read("word/document.xml"))
body = root.find("w:body", NS)
blocks = conv.body_blocks(body)
text, meta = emit(blocks)
title = meta.get("title") or esc(pkg.core.get("title", "")) or esc(args.docx.stem)
subtitle = meta.get("subtitle")
lang = (args.lang or pkg.lang or "en").lower()
label = args.label or re.sub(r"#\w+\[(.*?)\]", r"\1", title).upper()
if len(label) > 55: # running-header budget: keep the first words
words = label.split()
while len(" ".join(words)) > 55 and len(words) > 1:
words.pop()
label = " ".join(words)
if conv.dropped_fields:
review.append("Word fields dropped (the template generates its own): " + ", ".join(sorted(conv.dropped_fields)))
comments = "word/comments.xml" in pkg.zf.namelist()
if comments:
n = pkg.zf.read("word/comments.xml").count(b"<w:comment ")
if n:
review.append(f"{n} Word comment(s) not converted; read them in Word before deleting the source")
if conv.dropped_labels:
review.append(f"{conv.dropped_labels} short text-box label(s) drawn over pictures were dropped; number the items in the caption or list instead")
if conv.promoted:
review.append("paragraphs formatted to look like headings became headings: " + "; ".join(conv.promoted[:6]))
if any(b.kind == "textbox" for b in blocks):
review.append("text boxes became #note[...] blocks after the paragraph that anchored them")
header = [
f"// Draft generated by brand/tools/docx2typ.py from \"{args.docx.name}\" on {dt.date.today().isoformat()}.",
"// REVIEW before the first release, then delete this block:",
*[f"// - {item}" for item in dict.fromkeys(review)],
"// - read the whole draft against the Word original (layout tricks may hide meaning)",
"// - shorten callouts and captions to the budgets in brand/docs/TEMPLATE_GUIDE.md",
"",
'#import "/brand/templates/technical.typ": *',
"",
"#show: technical-document.with(",
f" title: [{title}],",
]
if subtitle:
header.append(f" subtitle: [{subtitle}],")
header += [
f" document-label: [{label}],",
f' lang: "{lang}",',
f' density: "{args.density}",',
")",
"",
]
doc_dir.mkdir(parents=True, exist_ok=True)
target.write_text("\n".join(header) + "\n" + text, encoding="utf-8", newline="\n")
print(f"wrote {target.relative_to(Path.cwd())}: {len(blocks)} blocks, {conv.image_count} picture(s), {len(set(review))} review item(s)")
for item in dict.fromkeys(review):
print(f" review: {item}")
return 0
if __name__ == "__main__":
sys.exit(main())
+274
View File
@@ -0,0 +1,274 @@
#!/usr/bin/env python3
"""Check content documents against the AIMsight authoring rules.
python brand/tools/lint.py # all documents/*/*.typ
python brand/tools/lint.py station-manual # one document folder
python brand/tools/lint.py --release # also refuse TODO markers
python brand/tools/lint.py --paths a.typ # any files
Content files carry wording, data and semantic choices; geometry, colours and
typography belong to brand/. See brand/docs/TEMPLATE_GUIDE.md. Errors fail
the build; warnings are printed:
- layout and styling in content (place, move, colours, fonts, page settings)
- `*` list markers, logo files, relative picture paths
- bare #image blocks and tables whose header row is not table.header
- text budgets of TEMPLATE_GUIDE.md (titles, slide bullets, callouts, captions)
- translations (main.<lang>.typ) whose chapter structure differs from main.typ
A line can opt out of one rule with a trailing comment:
#place(...) // lint: allow place
"""
from __future__ import annotations
import argparse
import re
import sys
from pathlib import Path
ROOT = Path.cwd()
# (rule id, severity, regex, message)
RULES = [
("place", "error", re.compile(r"#place\("), "manual positioning; add a reusable helper to the brand instead"),
("move", "error", re.compile(r"#move\("), "manual nudging; layout belongs in brand/theme/geometry.typ"),
("colour", "error", re.compile(r"\b(rgb|cmyk|luma)\(\s*\"?#?[0-9A-Fa-f]"), "raw colour; use the brand palette names (steel, ink, quiet, ...)"),
("page", "error", re.compile(r"#set\s+page\("), "page geometry is owned by the template"),
("font", "error", re.compile(r"#set\s+text\([^)]*\bfont\s*:"), "fonts are owned by the template"),
("star-list", "error", re.compile(r"^\s*\*\s+\S"), "use '-' for list items ('*' starts strong text in Typst)"),
("logo", "error", re.compile(r"AIMsight_logo|AIMsight_mark"), "logos come from the template; do not reference logo files"),
("relative-path", "warning", re.compile(r"#(fig|screenshot|icon|brochure-photo|engineering-svg)\(\s*\"(?!/)"),
"string paths are resolved from brand/templates; use '/documents/<doc>/...' or pass image(\"...\")"),
("bare-image", "warning", re.compile(r"^\s*#image\("), "bare picture; use #fig(...) (caption, centring) or #icon(...) inside text"),
("nudge", "warning", re.compile(r"\b(dx|dy)\s*:\s*-?[\d.]+\s*(mm|pt|cm|em)"), "point/mm offsets in content"),
("grid", "warning", re.compile(r"#grid\("), "layout grid in content; prefer a template helper (fig-row, data-table)"),
("legacy", "warning", re.compile(r"#import\s+\"[^\"]*(AIMsight(_v2|_10pt|_11pt)?\.typ)\""), "legacy template import; migrate to /brand/templates/technical.typ"),
]
RELEASE_RULES = [
("todo", "error", re.compile(r"#todo\b|#placeholder-figure\b"), "unfinished content in a release build"),
]
ALLOW = re.compile(r"//\s*lint:\s*allow\s+([\w-]+)")
# Text budgets from TEMPLATE_GUIDE.md: function -> field -> (unit, maximum).
# Units: "chars" or "words". Positional content (callouts) uses field "body".
BUDGETS = {
"technical-document": {"title": ("chars", 75), "subtitle": ("chars", 100), "document-label": ("chars", 55)},
"brochure-cover": {"kicker": ("chars", 40), "title": ("chars", 90), "strapline": ("chars", 55),
"intro-title": ("chars", 55), "intro-body": ("words", 150), "highlight": ("words", 28),
"closing-note": ("words", 55)},
"brochure-page": {"kicker": ("words", 6), "title": ("chars", 80), "body": ("words", 320)},
"brochure-final-page": {"kicker": ("words", 6), "title": ("chars", 80), "body": ("words", 320)},
"title-slide": {"kicker": ("words", 6), "title": ("chars", 75), "subtitle": ("chars", 110)},
"section-slide": {"title": ("chars", 55), "subtitle": ("chars", 100)},
"statement-slide": {"title": ("words", 10), "statement": ("words", 22), "support": ("words", 30)},
"content-slide": {"title": ("words", 11), "body": ("words", 70)},
"two-column-slide": {"title": ("words", 11)},
"image-slide": {"title": ("words", 12), "caption": ("words", 25)},
"gallery-slide": {"title": ("words", 10)},
"metric-slide": {"title": ("words", 11), "lead": ("words", 25)},
"comparison-slide": {"title": ("words", 10)},
"case-study-slide": {"title": ("words", 11), "result": ("words", 15)},
"quote-slide": {"quote": ("words", 45), "attribution": ("words", 10)},
"closing-slide": {"title": ("words", 10), "subtitle": ("words", 16)},
"note": {"body": ("words", 90)}, "tip": {"body": ("words", 90)}, "caution": {"body": ("words", 90)},
"warning": {"body": ("words", 90)}, "danger": {"body": ("words", 90)},
"fig": {"caption": ("words", 25)}, "screenshot": {"caption": ("words", 25)}, "fig-row": {"caption": ("words", 40)},
}
SLIDE_BULLETS = {"content-slide": (5, 16)} # max bullets, max words per bullet
def strip_comment(line: str) -> str:
return re.split(r"(?<!:)//", line, maxsplit=1)[0]
def plain(text: str) -> str:
text = re.sub(r"#\w[\w.-]*(\([^)]*\))?", " ", text) # function calls
text = re.sub(r"\$[^$]*\$", " x ", text) # math counts as one word
return re.sub(r"[\[\]{}*_\\]", " ", text)
def matching(text: str, start: int, open_ch: str, close_ch: str) -> int:
"""Index of the bracket closing text[start] (an open_ch), skipping strings and comments."""
depth, i, n = 0, start, len(text)
while i < n:
c = text[i]
if c == '"':
i += 1
while i < n and text[i] != '"':
i += 2 if text[i] == "\\" else 1
elif text.startswith("//", i) and (i == 0 or text[i - 1] != ":"):
i = text.find("\n", i)
if i < 0:
return n
continue
elif c in "([{":
depth += 1
elif c in ")]}":
depth -= 1
if depth == 0:
return i
i += 1
return n
def call_fields(text: str, name: str):
"""Yield (line, field, value) for named and trailing content arguments of #name(...)[...]."""
# Plain calls (#note[...]) and show rules (#show: technical-document.with(...)).
for m in re.finditer(r"(?:#|show:\s*)" + re.escape(name) + r"(?![\w-])(\.with)?", text):
i = m.end()
line = text.count("\n", 0, m.start()) + 1
if i < len(text) and text[i] == "(":
end = matching(text, i, "(", ")")
args = text[i + 1:end]
j = 0
while j < len(args):
fm = re.compile(r"(?:^|[,(\s])([a-z][\w-]*)\s*:\s*").search(args, j)
if not fm:
break
k = fm.end()
if k < len(args) and args[k] in "[\"":
close = matching(args, k, args[k], "]") if args[k] == "[" else args.find('"', k + 1)
yield line, fm.group(1), args[k + 1:close]
j = close + 1
elif k < len(args) and args[k] in "({":
j = matching(args, k, args[k], ")") + 1
else:
j = k
i = end + 1
if i < len(text) and text[i] == "[":
end = matching(text, i, "[", "]")
yield line, "body", text[i + 1:end]
def check_budgets(path: Path, text: str) -> list[str]:
out = []
for fn, fields in BUDGETS.items():
for line, field, value in call_fields(text, fn):
if field not in fields:
continue
unit, limit = fields[field]
p = plain(value)
size = len(" ".join(p.split())) if unit == "chars" else len(p.split())
if size > limit:
out.append(f"{path.relative_to(ROOT)}:{line}: warning: [budget] {fn} {field}: {size} {unit} (budget {limit}); shorten or split")
for fn, (max_bullets, max_words) in SLIDE_BULLETS.items():
for line, field, value in call_fields(text, fn):
if field != "body":
continue
bullets = [b for b in value.splitlines() if re.match(r"\s*[-+]\s", b)]
if len(bullets) > max_bullets:
out.append(f"{path.relative_to(ROOT)}:{line}: warning: [budget] {fn}: {len(bullets)} bullets (budget {max_bullets}); split the slide")
long = [b for b in bullets if len(plain(b).split()) > max_words + 1]
if long:
out.append(f"{path.relative_to(ROOT)}:{line}: warning: [budget] {fn}: {len(long)} bullet(s) over {max_words} words")
return out
def check_table_headers(path: Path, text: str) -> list[str]:
out = []
for m in re.finditer(r"#table\(", text):
end = matching(text, m.end() - 1, "(", ")")
body = text[m.end():end]
if "table.header" in body:
continue
cols = re.search(r"columns:\s*(\d+|\(([^()]*)\))", body)
if not cols:
continue
ncols = int(cols.group(1)) if cols.group(1).isdigit() else len([c for c in cols.group(2).split(",") if c.strip()])
cells = re.findall(r"\[(#strong\[[^\]]*\]|[^\[\]]*)\]", body[cols.end():])
if ncols and len(cells) >= ncols and all(c.startswith("#strong[") for c in cells[:ncols]):
line = text.count("\n", 0, m.start()) + 1
out.append(f"{path.relative_to(ROOT)}:{line}: warning: [table-header] bold first row: wrap it in table.header(...) "
"so it repeats after page breaks, or use #data-table")
return out
STRUCTURE = re.compile(
r"^(=+)\s|^#(brochure-cover|brochure-page|brochure-final-page|[a-z-]+-slide|fig|fig-row|screenshot|data-table|table)\(",
re.M,
)
def structure(text: str) -> list[str]:
"""Headings (by level), brochure pages, slides, figures and tables, in order."""
return [m.group(1) or m.group(2) for m in STRUCTURE.finditer(text)]
def check_translations(folder: Path) -> list[str]:
main = folder / "main.typ"
variants = sorted(folder.glob("main.??.typ"))
if not main.exists() or not variants:
return []
ref = structure(main.read_text(encoding="utf-8"))
out = []
for v in variants:
other = structure(v.read_text(encoding="utf-8"))
if other != ref:
first = next((i for i, (a, b) in enumerate(zip(ref, other)) if a != b), min(len(ref), len(other)))
want = ref[first] if first < len(ref) else "end of document"
got = other[first] if first < len(other) else "end of document"
out.append(f"{v.relative_to(ROOT)}: warning: [translation] structure differs from main.typ at element "
f"{first + 1} (main.typ has {want!r}, this file {got!r}); the translation is out of date")
return out
def lint_file(path: Path, rules) -> tuple[int, int, list[str]]:
errors = warnings = 0
messages = []
text = path.read_text(encoding="utf-8")
in_raw = False
for no, line in enumerate(text.splitlines(), 1):
if line.lstrip().startswith("```"):
in_raw = not in_raw
continue
if in_raw:
continue
allowed = set(ALLOW.findall(line))
code = strip_comment(line)
for rule, severity, rx, msg in rules:
if rule in allowed or not rx.search(code):
continue
messages.append(f"{path.relative_to(ROOT)}:{no}: {severity}: [{rule}] {msg}")
if severity == "error":
errors += 1
else:
warnings += 1
extra = check_budgets(path, text) + check_table_headers(path, text)
return errors, warnings + len(extra), messages + extra
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("documents", nargs="*")
parser.add_argument("--release", action="store_true")
parser.add_argument("--paths", nargs="*", default=None, help="lint these files instead of documents/")
parser.add_argument("--quiet", action="store_true", help="print errors only")
args = parser.parse_args()
if args.paths is not None:
files = [Path(p).resolve() for p in args.paths]
folders = []
else:
folders = [ROOT / "documents" / d for d in args.documents] if args.documents else \
sorted(p for p in (ROOT / "documents").glob("*") if p.is_dir())
files = sorted(f for folder in folders for f in folder.rglob("*.typ"))
rules = RULES + (RELEASE_RULES if args.release else [])
errors = warnings = 0
messages = []
for f in files:
e, w, m = lint_file(f, rules)
errors, warnings, messages = errors + e, warnings + w, messages + m
for folder in folders:
t = check_translations(folder)
warnings += len(t)
messages += t
for m in messages:
if not args.quiet or ": error:" in m:
print(m)
if errors or (warnings and not args.quiet):
print(f"lint: {errors} error(s), {warnings} warning(s) in {len(files)} file(s)")
return 1 if errors else 0
if __name__ == "__main__":
sys.exit(main())
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/env python3
"""Start a new document in a factory from a brand starter.
Run from the factory root:
python brand/tools/new.py --list
python brand/tools/new.py user-manual monitoring-dashboard --title "AIMsight Monitoring Dashboard"
python brand/tools/new.py report rapport-planches --title "Rapport d'installation" --lang fr
python brand/tools/new.py translate station-manual --lang fr # main.fr.typ from main.typ
Creates documents/<slug>/main.typ from brand/starters/<starter>/main.typ.
Starters: user-manual, report, note (technical family), brochure, deck.
"""
from __future__ import annotations
import argparse
import re
import sys
from pathlib import Path
STARTERS = Path(__file__).resolve().parent.parent / "starters"
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("starter", nargs="?")
ap.add_argument("slug", nargs="?", help="folder name under documents/, e.g. cam-user-manual")
ap.add_argument("--title", help="document title")
ap.add_argument("--label", help="running-header label (default: title in capitals)")
ap.add_argument("--lang", default="en", choices=["en", "fr", "de", "es", "it"])
ap.add_argument("--list", action="store_true")
args = ap.parse_args()
available = sorted(p.name for p in STARTERS.iterdir() if (p / "main.typ").exists())
if args.starter == "translate":
source = Path.cwd() / "documents" / (args.slug or "") / "main.typ"
if not args.slug or not source.exists():
sys.exit("usage: new.py translate <slug> --lang <xx> (documents/<slug>/main.typ must exist)")
target = source.with_name(f"main.{args.lang}.typ")
if target.exists():
sys.exit(f"{target} already exists")
text = source.read_text(encoding="utf-8")
text, n = re.subn(r'\blang:\s*"[a-z]{2}"', f'lang: "{args.lang}"', text, count=1)
if n == 0: # no lang yet: add it to whichever family the document uses
for setup in ("technical-document", "brochure", "presentation"):
text = text.replace(f"#show: {setup}.with(", f'#show: {setup}.with(\n lang: "{args.lang}",', 1)
target.write_text(text, encoding="utf-8", newline="\n")
print(f"created {target.relative_to(Path.cwd())}: translate the text, keep the headings in step "
f"(lint compares the structure with main.typ)")
return 0
if args.list or not args.starter:
print("starters: " + ", ".join(available))
return 0
if args.starter not in available:
sys.exit(f"unknown starter {args.starter!r}; choose from {', '.join(available)}")
if not args.slug or not re.fullmatch(r"[a-z0-9][a-z0-9-]*", args.slug):
sys.exit("give a slug of lowercase letters, digits and dashes")
target = Path.cwd() / "documents" / args.slug / "main.typ"
if target.exists():
sys.exit(f"{target} already exists")
title = args.title or args.slug.replace("-", " ").title()
label = args.label or title.upper()
text = (STARTERS / args.starter / "main.typ").read_text(encoding="utf-8")
for key, value in {"title": title, "label": label, "lang": args.lang, "slug": args.slug}.items():
text = text.replace("{{" + key + "}}", value)
target.parent.mkdir(parents=True)
(target.parent / "images").mkdir()
target.write_text(text, encoding="utf-8", newline="\n")
print(f"created {target.relative_to(Path.cwd())}; build it with: python brand/tools/build.py {args.slug}")
return 0
if __name__ == "__main__":
sys.exit(main())
+254
View File
@@ -0,0 +1,254 @@
#!/usr/bin/env python3
"""Live preview of the documents in a browser, refreshed on every save.
python brand/tools/preview.py # http://127.0.0.1:8770
python brand/tools/preview.py --port 9000
Lists every document (and language) of the factory; a document page shows
all its pages and re-renders within a second of any change to the document,
the brand, captures/ or assets/. Compile errors appear in the page. The PDF
button builds a PDF with the same git stamping as build.py.
Run from a factory root, or from the brand repository itself to preview
examples/ and tests/. Works in any browser, including the Claude desktop
app's browser pane; VS Code users can also use Tinymist's preview.
Standard library only (Python 3.11+). Requires `typst` on PATH.
"""
from __future__ import annotations
import argparse
import html
import json
import re
import subprocess
import sys
import threading
import time
import urllib.parse
from dataclasses import dataclass
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import build # noqa: E402 (shared document discovery and git stamping)
ROOT = Path.cwd()
OUT = ROOT / "build" / "preview"
@dataclass
class Entry:
ident: str # URL id: output stem (station-manual-fr) or example name
title: str
path: Path
slug: str | None # factory document slug (git stamping), None for brand examples
watch: list[Path]
version: int = 0
signature: tuple = ()
pages: int = 0
error: str = ""
seconds: float = 0.0
def discover() -> list[Entry]:
entries = []
if (ROOT / "documents").is_dir():
shared = [ROOT / p for p in ("brand", "captures", "assets")]
for doc in build.find_documents():
entries.append(Entry(doc.output_stem, doc.ident, doc.path, doc.slug, [doc.path.parent, *shared]))
else: # the brand repository: examples and tests
shared = [ROOT / p for p in ("templates", "theme", "compat", "assets", "fonts")]
for path in sorted([*ROOT.glob("examples/*.typ"), *ROOT.glob("tests/*.typ")]):
entries.append(Entry(path.stem, str(path.relative_to(ROOT)), path, None, [path.parent, *shared]))
return entries
def signature(paths: list[Path]) -> tuple:
stamps = []
for base in paths:
if base.is_file():
stamps.append(base.stat().st_mtime_ns)
elif base.is_dir():
for f in base.rglob("*"):
if f.is_file() and "_tmp" not in f.parts and "__pycache__" not in f.parts:
stamps.append(f.stat().st_mtime_ns)
return (len(stamps), max(stamps, default=0), sum(stamps) % 1_000_000_007)
LOCK = threading.Lock()
def refresh(entry: Entry) -> None:
"""Recompile the entry's SVG pages if a watched file changed."""
with LOCK:
sig = signature(entry.watch)
if sig == entry.signature:
return
entry.signature = sig
target = OUT / entry.ident
target.mkdir(parents=True, exist_ok=True)
for old in target.glob("page-*.svg"):
old.unlink()
inputs = build.stamp(entry.slug) if entry.slug else {}
args = build.typst_args(inputs) if entry.slug else ["--root", str(ROOT), *build.font_args()]
start = time.monotonic()
res = subprocess.run(["typst", "compile", *args, "--format", "svg", str(entry.path), str(target / "page-{0p}.svg")],
capture_output=True, text=True)
entry.seconds = time.monotonic() - start
entry.error = res.stderr.strip() if res.returncode != 0 else ""
entry.pages = len(list(target.glob("page-*.svg")))
entry.version += 1
def build_pdf(entry: Entry) -> tuple[Path | None, str]:
inputs = build.stamp(entry.slug) if entry.slug else {}
args = build.typst_args(inputs) if entry.slug else ["--root", str(ROOT), *build.font_args()]
pdf = OUT / f"{entry.ident}.pdf"
res = subprocess.run(["typst", "compile", *args, str(entry.path), str(pdf)], capture_output=True, text=True)
return (pdf if res.returncode == 0 else None), res.stderr
STYLE = """
:root { --bg: #e9eef0; --ink: #252D33; --steel: #074A5E; --quiet: #657980; --card: #fff; --err: #E41D25; }
* { box-sizing: border-box; }
body { margin: 0; font: 14px/1.4 Inter, "Segoe UI", system-ui, sans-serif; background: var(--bg); color: var(--ink); }
header { position: sticky; top: 0; z-index: 2; display: flex; gap: 12px; align-items: center; flex-wrap: wrap;
padding: 10px 16px; background: var(--steel); color: #fff; }
header a, header button { color: #fff; background: rgba(255,255,255,.12); border: 1px solid rgba(255,255,255,.35);
border-radius: 4px; padding: 4px 10px; text-decoration: none; font: inherit; cursor: pointer; }
header .meta { opacity: .8; font-size: 12px; }
main { padding: 16px; }
.pages { display: flex; flex-direction: column; align-items: center; gap: 14px; }
.pages img { background: #fff; box-shadow: 0 1px 4px rgba(0,0,0,.25); width: min(100%, var(--w, 900px)); }
.error { white-space: pre-wrap; font: 12px/1.45 Consolas, monospace; background: #fff1f2; color: #7a1016;
border: 1px solid var(--err); border-radius: 4px; padding: 12px; max-width: 1100px; margin: 0 auto 16px; }
ul.docs { list-style: none; padding: 0; max-width: 900px; margin: 0 auto; }
ul.docs li { background: var(--card); margin: 6px 0; border-radius: 4px; padding: 10px 14px; display: flex; justify-content: space-between; }
ul.docs a { color: var(--steel); font-weight: 600; text-decoration: none; }
"""
def page_index(entries: list[Entry]) -> str:
items = "".join(
f'<li><a href="/doc/{urllib.parse.quote(e.ident)}">{html.escape(e.title)}</a>'
f'<span class="meta">{html.escape(str(e.path.relative_to(ROOT)))}</span></li>' for e in entries)
return f"""<!doctype html><html><head><meta charset="utf-8"><title>Documents</title>
<meta name="viewport" content="width=device-width, initial-scale=1"><style>{STYLE}</style></head>
<body><header><strong>AIMsight documents</strong><span class="meta">{html.escape(str(ROOT))}</span></header>
<main><ul class="docs">{items}</ul></main></body></html>"""
def page_doc(entry: Entry, siblings: list[Entry]) -> str:
langs = "".join(f'<a href="/doc/{urllib.parse.quote(s.ident)}">{html.escape(s.title.split(":")[-1] if ":" in s.title else "main")}</a>'
for s in siblings if s.slug == entry.slug and entry.slug and s is not entry)
ident = json.dumps(entry.ident)
return f"""<!doctype html><html><head><meta charset="utf-8"><title>{html.escape(entry.title)}</title>
<meta name="viewport" content="width=device-width, initial-scale=1"><style>{STYLE}</style></head>
<body><header><a href="/">&larr; All</a><strong>{html.escape(entry.title)}</strong>{langs}
<button onclick="zoom(-1)">&minus;</button><button onclick="zoom(1)">+</button>
<a href="/pdf/{urllib.parse.quote(entry.ident)}" target="_blank">PDF</a><span class="meta" id="meta">compiling…</span></header>
<main><div id="error" class="error" hidden></div><div class="pages" id="pages"></div></main>
<script>
const id = {ident}; let version = -1; let width = 900;
function zoom(d) {{ width = Math.max(400, Math.min(2000, width + d * 150)); document.documentElement.style.setProperty('--w', width + 'px'); }}
async function poll() {{
try {{
const s = await (await fetch('/api/' + encodeURIComponent(id))).json();
document.getElementById('meta').textContent = s.pages + ' pages · ' + s.seconds.toFixed(1) + ' s · revision ' + (s.revision || '–');
const err = document.getElementById('error');
err.hidden = !s.error; err.textContent = s.error;
if (s.version !== version && !s.error) {{
version = s.version;
const box = document.getElementById('pages'); const y = window.scrollY; box.innerHTML = '';
for (let i = 1; i <= s.pages; i++) {{
const img = document.createElement('img');
img.src = '/svg/' + encodeURIComponent(id) + '/' + i + '?v=' + version; img.alt = 'Page ' + i; box.appendChild(img);
}}
window.scrollTo(0, y);
}}
}} catch (e) {{ document.getElementById('meta').textContent = 'preview server stopped'; }}
setTimeout(poll, 1000);
}}
poll();
</script></body></html>"""
def make_handler(entries: list[Entry]):
by_id = {e.ident: e for e in entries}
def rediscover() -> None:
# New documents appear without restarting the server.
for e in discover():
if e.ident not in by_id:
entries.append(e)
by_id[e.ident] = e
class Handler(BaseHTTPRequestHandler):
def log_message(self, *args): # keep the console quiet
pass
def send(self, code: int, body: bytes, ctype: str) -> None:
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self): # noqa: N802
path = urllib.parse.unquote(urllib.parse.urlparse(self.path).path)
parts = [p for p in path.split("/") if p]
if not parts:
rediscover()
return self.send(200, page_index(entries).encode(), "text/html; charset=utf-8")
if len(parts) > 1 and parts[1] not in by_id:
rediscover()
entry = by_id.get(parts[1]) if len(parts) > 1 else None
if entry is None:
return self.send(404, b"not found", "text/plain")
if parts[0] == "doc":
return self.send(200, page_doc(entry, entries).encode(), "text/html; charset=utf-8")
if parts[0] == "api":
refresh(entry)
revision = build.stamp(entry.slug)["revision"] if entry.slug else ""
status = {"version": entry.version, "pages": entry.pages, "error": entry.error,
"seconds": entry.seconds, "revision": revision}
return self.send(200, json.dumps(status).encode(), "application/json")
if parts[0] == "svg" and len(parts) == 3 and parts[2].isdigit():
f = OUT / entry.ident / f"page-{int(parts[2]):0{len(str(entry.pages))}d}.svg"
if not f.exists():
f = next((OUT / entry.ident).glob(f"page-*{int(parts[2])}.svg"), f)
if f.exists():
return self.send(200, f.read_bytes(), "image/svg+xml")
return self.send(404, b"no such page", "text/plain")
if parts[0] == "pdf":
pdf, err = build_pdf(entry)
if pdf is None:
return self.send(500, err.encode(), "text/plain; charset=utf-8")
return self.send(200, pdf.read_bytes(), "application/pdf")
return self.send(404, b"not found", "text/plain")
return Handler
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--port", type=int, default=8770)
ap.add_argument("--host", default="127.0.0.1")
args = ap.parse_args()
entries = discover()
if not entries:
sys.exit("No documents found.")
OUT.mkdir(parents=True, exist_ok=True)
server = ThreadingHTTPServer((args.host, args.port), make_handler(entries))
print(f"Preview of {len(entries)} document(s): http://{args.host}:{args.port}/ (Ctrl+C to stop)", flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
return 0
if __name__ == "__main__":
sys.exit(main())
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env python3
"""Attach the built PDFs to the Gitea release of the current tag (CI only).
Called by the factory workflow after `build.py --release` on a tag push:
python3 brand/tools/release.py
Uses the variables Gitea Actions provides: GITHUB_SERVER_URL,
GITHUB_REPOSITORY, GITHUB_REF_NAME and the job token in GITEA_TOKEN (falls
back to GITHUB_TOKEN). Creates the release if it does not exist and replaces
assets with the same name, so re-running a job is harmless.
Standard library only.
"""
from __future__ import annotations
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path
def api(method: str, url: str, token: str, body: bytes | None = None, ctype: str = "application/json"):
req = urllib.request.Request(url, data=body, method=method)
req.add_header("Authorization", f"token {token}")
req.add_header("Accept", "application/json")
if body is not None:
req.add_header("Content-Type", ctype)
with urllib.request.urlopen(req) as res:
data = res.read()
return json.loads(data) if data else None
def main() -> int:
server = os.environ["GITHUB_SERVER_URL"].rstrip("/")
repo = os.environ["GITHUB_REPOSITORY"]
tag = os.environ["GITHUB_REF_NAME"]
token = os.environ.get("GITEA_TOKEN") or os.environ["GITHUB_TOKEN"]
base = f"{server}/api/v1/repos/{repo}"
try:
release = api("GET", f"{base}/releases/tags/{urllib.parse.quote(tag, safe='')}", token)
except urllib.error.HTTPError as err:
if err.code != 404:
raise
body = json.dumps({"tag_name": tag, "name": tag, "body": f"PDFs built from {tag}."}).encode()
release = api("POST", f"{base}/releases", token, body)
existing = {a["name"]: a["id"] for a in release.get("assets", [])}
pdfs = sorted(Path("build").glob("*.pdf"))
if not pdfs:
print("release: no PDFs in build/")
return 1
for pdf in pdfs:
if pdf.name in existing:
api("DELETE", f"{base}/releases/{release['id']}/assets/{existing[pdf.name]}", token)
boundary = uuid.uuid4().hex
payload = (
f"--{boundary}\r\nContent-Disposition: form-data; name=\"attachment\"; filename=\"{pdf.name}\"\r\n"
f"Content-Type: application/pdf\r\n\r\n"
).encode() + pdf.read_bytes() + f"\r\n--{boundary}--\r\n".encode()
api("POST", f"{base}/releases/{release['id']}/assets?name={urllib.parse.quote(pdf.name)}", token,
payload, f"multipart/form-data; boundary={boundary}")
print(f"release {tag}: attached {pdf.name}")
return 0
if __name__ == "__main__":
sys.exit(main())
+9
View File
@@ -0,0 +1,9 @@
[package]
name = "aimsight-brand"
version = "1.1.0"
entrypoint = "lib.typ"
authors = ["AIMsight SA"]
description = "AIMsight brochure, technical-document and presentation templates"
license = "Proprietary"
compiler = "0.14.0"
exclude = ["examples", "tests", "build", "tools/__pycache__"]