Skip to content

The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.

JavaScript

Render note PDFs on the server, with fonts that ship

OsintMeThatcdb44407d03e
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index ed90f5c..21d6e5f 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -58,14 +58,24 @@ jobs:
run: |
uv sync --frozen --no-dev --group release --no-install-project
uv run --no-sync python -m build --no-isolation
- - name: Sanity-check the wheel bundles the UI
+ - name: Sanity-check the wheel bundles the UI and PDF assets
run: |
python - <<'PY'
import glob, zipfile
whl = sorted(glob.glob("dist/*.whl"))[-1]
- n = [x for x in zipfile.ZipFile(whl).namelist() if x.startswith("azimut/static/")]
- assert n, "wheel is missing azimut/static/** — did the frontend build run?"
- print(f"{whl}: {len(n)} static files bundled")
+ names = set(zipfile.ZipFile(whl).namelist())
+ static = [name for name in names if name.startswith("azimut/static/")]
+ assert static, "wheel is missing azimut/static/** — did the frontend build run?"
+ required = {
+ "azimut/assets/fonts/NotoSerif-Regular.ttf",
+ "azimut/assets/fonts/APACHE-2.0.txt",
+ "azimut/assets/fonts/OFL.txt",
+ "azimut/assets/fonts/BITSTREAM-VERA.txt",
+ "azimut/assets/fonts/README.md",
+ }
+ missing = sorted(required - names)
+ assert not missing, f"wheel is missing PDF font assets: {missing}"
+ print(f"{whl}: {len(static)} static files and PDF font assets bundled")
PY
- uses: actions/upload-artifact@v4
with:
diff --git a/frontend/src/lib/mermaid.js b/frontend/src/lib/mermaid.js
index a1c4cc2..236c3c7 100644
--- a/frontend/src/lib/mermaid.js
+++ b/frontend/src/lib/mermaid.js
@@ -34,6 +34,16 @@ const CONFIG = {
},
};
+/**
+ * Per-diagram config for the PDF export, prepended to the source rather than
+ * initialised globally so the preview keeps its own settings. HTML labels are a
+ * `<foreignObject>` — HTML nested inside the picture — and a browser will not
+ * rasterise one out of an image element, so a diagram exported that way comes
+ * back with empty boxes where its text should be.
+ */
+const PLAIN_LABELS = '%%{init: {"flowchart": {"htmlLabels": false}, '
+ + '"class": {"htmlLabels": false}, "er": {"htmlLabels": false}} }%%\n';
+
let loading = null;
let sequence = 0;
@@ -46,6 +56,29 @@ function loadMermaid() {
return loading;
}
+/**
+ * One diagram drawn to a standalone SVG, with the size it wants to be.
+ *
+ * Mermaid sizes its output through a `max-width` style and a viewBox, neither of
+ * which a canvas reads, so the intrinsic size is put back on the element before
+ * the caller rasterises it.
+ */
+export async function renderMermaidSvg(source, { load = loadMermaid } = {}) {
+ const mermaid = await load();
+ const id = `azimut-mermaid-export-${(sequence += 1)}`;
+ const { svg } = await mermaid.render(id, `${PLAIN_LABELS}${source}`);
+ const element = new DOMParser().parseFromString(svg, 'image/svg+xml').documentElement;
+ const [, , boxWidth, boxHeight] = (element.getAttribute('viewBox') ?? '0 0 800 600')
+ .split(/[\s,]+/)
+ .map(Number);
+ const width = boxWidth || 800;
+ const height = boxHeight || 600;
+ element.setAttribute('width', String(width));
+ element.setAttribute('height', String(height));
+ element.removeAttribute('style');
+ return { svg: new XMLSerializer().serializeToString(element), width, height };
+}
+
function failed(node, message) {
node.classList.add('mermaid-failed');
const note = node.ownerDocument.createElement('p');
diff --git a/frontend/src/lib/mermaid.test.js b/frontend/src/lib/mermaid.test.js
index dbf7d71..523b2ce 100644
--- a/frontend/src/lib/mermaid.test.js
+++ b/frontend/src/lib/mermaid.test.js
@@ -1,7 +1,7 @@
import { Window } from 'happy-dom';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { markdownHtml } from './markdown.js';
-import { drawMermaidDiagrams } from './mermaid.js';
+import { drawMermaidDiagrams, renderMermaidSvg } from './mermaid.js';
function preview(markdown) {
const { document } = new Window();
@@ -67,3 +67,40 @@ describe('drawMermaidDiagrams', () => {
.toBe('Diagram not drawn: diagram support could not be loaded');
});
});
+
+describe('renderMermaidSvg', () => {
+ const window = new Window();
+
+ afterEach(() => vi.unstubAllGlobals());
+
+ function browser() {
+ vi.stubGlobal('DOMParser', window.DOMParser);
+ vi.stubGlobal('XMLSerializer', window.XMLSerializer);
+ }
+
+ it('gives the diagram the size a canvas can read', async () => {
+ browser();
+ const render = vi.fn().mockResolvedValue({
+ svg: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 180" style="max-width: 320px"></svg>',
+ });
+
+ const drawn = await renderMermaidSvg('flowchart LR\n A --> B', { load: async () => ({ render }) });
+
+ expect(drawn).toMatchObject({ width: 320, height: 180 });
+ expect(drawn.svg).toContain('width="320"');
+ expect(drawn.svg).toContain('height="180"');
+ // The style is what mermaid sizes itself with on screen, and what would
+ // shrink the diagram to nothing once it is drawn onto a canvas.
+ expect(drawn.svg).not.toContain('max-width');
+ });
+
+ it('turns HTML labels off, which an image element cannot rasterise', async () => {
+ browser();
+ const render = vi.fn().mockResolvedValue({ svg: '<svg viewBox="0 0 10 10"></svg>' });
+
+ await renderMermaidSvg('flowchart LR\n A --> B', { load: async () => ({ render }) });
+
+ expect(render.mock.calls[0][1]).toContain('"htmlLabels": false');
+ expect(render.mock.calls[0][1]).toContain('flowchart LR');
+ });
+});
diff --git a/frontend/src/lib/notebookPdf.js b/frontend/src/lib/notebookPdf.js
deleted file mode 100644
index 6221778..0000000
--- a/frontend/src/lib/notebookPdf.js
+++ /dev/null
@@ -1,126 +0,0 @@
-function escapeHtml(value) {
- return String(value)
- .replaceAll('&', '&amp;')
- .replaceAll('<', '&lt;')
- .replaceAll('>', '&gt;')
- .replaceAll('"', '&quot;')
- .replaceAll("'", '&#39;');
-}
-
-function mediaNote(document, message) {
- const note = document.createElement('p');
- note.className = 'pdf-media-note';
- note.textContent = message;
- return note;
-}
-
-/** Keep PDF export local: local images print, while remote media never loads. */
-export function prepareNotebookPdfContent(content, origin, document = globalThis.document) {
- const wrapper = document.createElement('div');
- wrapper.innerHTML = content;
-
- for (const source of wrapper.querySelectorAll('source')) source.remove();
- for (const element of wrapper.querySelectorAll('[srcset]')) element.removeAttribute('srcset');
- for (const element of wrapper.querySelectorAll('[style]')) {
- if (/url\s*\(/i.test(element.getAttribute('style'))) element.removeAttribute('style');
- }
-
- for (const video of wrapper.querySelectorAll('video, audio')) {
- video.replaceWith(mediaNote(document, 'Video not included in PDF.'));
- }
-
- for (const image of wrapper.querySelectorAll('img')) {
- const source = image.getAttribute('src');
- let isLocal = false;
- try {
- isLocal = new URL(source, origin).origin === origin;
- } catch {
- // An invalid source cannot be part of the export.
- }
- if (!isLocal) image.replaceWith(mediaNote(document, 'External image not included in PDF.'));
- }
-
- return wrapper.innerHTML;
-}
-
-export function notebookPdfHtml({ title, content, origin, document = globalThis.document }) {
- const safeTitle = escapeHtml(title || 'Case Notes');
- const body = prepareNotebookPdfContent(content, origin, document);
- return `<!doctype html>
-<html lang="en">
- <head>
- <meta charset="utf-8">
- <base href="${escapeHtml(origin)}/">
- <title>${safeTitle}</title>
- <style>
- @page { size: A4; margin: 18mm 16mm 20mm; }
- :root { color-scheme: light; }
- * { box-sizing: border-box; }
- body { margin: 0; color: #202124; background: #fff; font: 10.5pt/1.6 Georgia, 'Times New Roman', serif; }
- .document-header { margin-bottom: 11mm; padding-bottom: 5mm; border-bottom: 1.5pt solid #bd7a25; }
- .document-kicker { margin: 0 0 2mm; color: #8a5a1a; font: 600 8pt/1.2 Arial, sans-serif; letter-spacing: .12em; text-transform: uppercase; }
- h1 { margin: 0; color: #181818; font: 700 25pt/1.12 Arial, sans-serif; letter-spacing: -.025em; }
- h1, h2, h3, h4, h5, h6 { break-after: avoid; page-break-after: avoid; }
- h2 { margin: 9mm 0 3mm; color: #202124; font: 700 16pt/1.2 Arial, sans-serif; }
- h3 { margin: 7mm 0 2mm; font: 700 12pt/1.25 Arial, sans-serif; }
- h4, h5, h6 { margin: 5mm 0 2mm; font: 700 10.5pt/1.3 Arial, sans-serif; }
- p, ul, ol, blockquote, pre, table { margin: 0 0 4mm; }
- ul, ol { padding-left: 6mm; }
- li + li { margin-top: 1mm; }
- a { color: #6d4515; text-decoration-color: #bd7a25; }
- blockquote { padding: 1mm 0 1mm 4mm; border-left: 2pt solid #bd7a25; color: #555; }
- code { padding: .15em .35em; border-radius: 2pt; background: #f4f1ed; font: 8.8pt/1.45 'SFMono-Regular', Consolas, monospace; }
- pre { overflow: hidden; padding: 3mm; border: .5pt solid #ddd6cc; border-radius: 2pt; background: #f8f6f3; white-space: pre-wrap; }
- pre code { padding: 0; background: transparent; }
- table { width: 100%; border-collapse: collapse; font-size: 9pt; break-inside: avoid; page-break-inside: avoid; }
- th, td { padding: 2mm 2.5mm; border: .5pt solid #d8d1c8; text-align: left; vertical-align: top; }
- th { background: #f1ece5; font-family: Arial, sans-serif; }
- tr { break-inside: avoid; page-break-inside: avoid; }
- img { display: block; max-width: 100%; height: auto; margin: 0 0 4mm; border-radius: 2pt; break-inside: avoid; page-break-inside: avoid; }
- .mermaid-diagram { margin: 0 0 4mm; padding: 3mm; border: .5pt solid #ddd6cc; border-radius: 2pt; text-align: center; break-inside: avoid; page-break-inside: avoid; }
- .mermaid-diagram svg { max-width: 100%; height: auto; }
- .mermaid-diagram pre { margin: 0; padding: 0; border: 0; background: transparent; text-align: left; }
- .mermaid-error { color: #777; font-style: italic; text-align: left; }
- .markdown-image.align-center { margin-right: auto; margin-left: auto; }
- .markdown-image.align-right { margin-right: 0; margin-left: auto; }
- .markdown-align.align-center { text-align: center; }
- .markdown-align.align-right { text-align: right; }
- .entity-ref { color: #6d4515; font-weight: 700; }
- .broken-ref, .pdf-media-note { color: #777; font-style: italic; }
- .pdf-media-note { padding: 2mm 3mm; border-left: 2pt solid #d8d1c8; background: #faf8f5; }
- .document-footer { position: fixed; right: 0; bottom: -13mm; left: 0; color: #777; font: 8pt Arial, sans-serif; }
- @media print { a { color: inherit; } }
- </style>
- </head>
- <body>
- <header class="document-header"><p class="document-kicker">Azimut notes</p><h1>${safeTitle}</h1></header>
- <main>${body}</main>
- <footer class="document-footer">Generated locally from case notes</footer>
- </body>
-</html>`;
-}
-
-/** Open the browser's Save-as-PDF flow from a user gesture. */
-export function downloadNotebookPdf({ title, content }) {
- const printWindow = window.open('', '_blank');
- if (!printWindow) return false;
-
- const origin = window.location.origin;
- printWindow.document.open();
- printWindow.addEventListener('load', () => {
- const images = Array.from(printWindow.document.images ?? []);
- Promise.all(images.map((image) => image.complete
- ? Promise.resolve()
- : new Promise((resolve) => {
- image.addEventListener('load', resolve, { once: true });
- image.addEventListener('error', resolve, { once: true });
- })))
- .then(() => {
- printWindow.focus();
- printWindow.print();
- });
- }, { once: true });
- printWindow.document.write(notebookPdfHtml({ title, content, origin, document: printWindow.document }));
- printWindow.document.close();
- return true;
-}
diff --git a/frontend/src/lib/notebookPdf.test.js b/frontend/src/lib/notebookPdf.test.js
deleted file mode 100644
index 6ef2dca..0000000
--- a/frontend/src/lib/notebookPdf.test.js
+++ /dev/null
@@ -1,72 +0,0 @@
-import { Window } from 'happy-dom';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-import { downloadNotebookPdf, notebookPdfHtml, prepareNotebookPdfContent } from './notebookPdf.js';
-
-const origin = 'http://127.0.0.1:8477';
-
-afterEach(() => vi.unstubAllGlobals());
-
-describe('notebook PDF export', () => {
- it('keeps local case images and omits remote media', () => {
- const document = new Window().document;
- const content = prepareNotebookPdfContent(
- '<img src="/files/case-1/media/map.png" srcset="https://example.test/[email protected] 2x"><img src="https://example.test/map.png"><video src="/files/case-1/media/clip.mp4"></video>',
- origin,
- document,
- );
-
- expect(content).toContain('/files/case-1/media/map.png');
- expect(content).not.toContain('srcset=');
- expect(content).not.toContain('https://example.test/map.png');
- expect(content).toContain('External image not included in PDF.');
- expect(content).toContain('Video not included in PDF.');
- });
-
- it('prints drawn diagrams as inline SVG', () => {
- const document = new Window().document;
- const content = prepareNotebookPdfContent(
- '<div class="mermaid-diagram" data-processed="true"><svg><text>Confirmed</text></svg></div>',
- origin,
- document,
- );
-
- expect(content).toContain('<svg>');
- expect(content).toContain('Confirmed');
- });
-
- it('builds a print-ready A4 document with the note title', () => {
- const document = new Window().document;
- const html = notebookPdfHtml({
- title: 'Field Notes',
- content: '<h2>Finding</h2><p>Confirmed.</p>',
- origin,
- document,
- });
-
- expect(html).toContain('@page { size: A4;');
- expect(html).toContain('<title>Field Notes</title>');
- expect(html).toContain('<h1>Field Notes</h1>');
- expect(html).toContain('<h2>Finding</h2>');
- });
-
- it('opens a print window from the download action', async () => {
- const document = new Window().document;
- let onLoad;
- const printWindow = {
- document,
- addEventListener: (_type, callback) => { onLoad = callback; },
- focus: vi.fn(),
- print: vi.fn(),
- };
- const open = vi.fn(() => printWindow);
- vi.stubGlobal('window', { location: { origin }, open });
-
- expect(downloadNotebookPdf({ title: 'Case Notes', content: '<p>Ready.</p>' })).toBe(true);
- expect(open).toHaveBeenCalledWith('', '_blank');
-
- onLoad();
- await Promise.resolve();
- expect(printWindow.focus).toHaveBeenCalledOnce();
- expect(printWindow.print).toHaveBeenCalledOnce();
- });
-});
diff --git a/frontend/src/lib/notesExport.js b/frontend/src/lib/notesExport.js
new file mode 100644
index 0000000..37fcff7
--- /dev/null
+++ b/frontend/src/lib/notesExport.js
@@ -0,0 +1,89 @@
+/**
+ * Exporting notes as PDF.
+ *
+ * The document itself is built by the backend (`engine/notes_pdf.py`), which
+ * reads each note's Markdown from disk rather than this preview: no print
+ * dialog, no popup to allow, and a whole selection of notes in one request.
+ *
+ * What is left here is the one thing a server cannot do. Mermaid is JavaScript,
+ * so the export asks which fences the selection holds, draws each one in this
+ * tab, and posts the pictures back under the keys it was given.
+ */
+
+import { api } from './api.js';
+import { renderMermaidSvg } from './mermaid.js';
+
+/** Rasterised at twice the page size, so a diagram is not soft in print. */
+const DIAGRAM_SCALE = 2;
+const MAX_DIAGRAM_EDGE = 2400;
+
+/**
+ * Draw an SVG onto a canvas and hand back the PNG, base64 without its header.
+ *
+ * Diagrams are rendered with HTML labels off (see lib/mermaid.js), because a
+ * `<foreignObject>` is HTML inside the picture and browsers refuse to rasterise
+ * one out of an image element — the diagram would come back with empty boxes.
+ */
+export function rasterise(svg, { width, height }) {
+ return new Promise((resolve, reject) => {
+ const scale = Math.min(DIAGRAM_SCALE, MAX_DIAGRAM_EDGE / Math.max(width, height, 1));
+ const canvas = document.createElement('canvas');
+ canvas.width = Math.max(1, Math.round(width * scale));
+ canvas.height = Math.max(1, Math.round(height * scale));
+ const image = new Image();
+ image.addEventListener('load', () => {
+ const context = canvas.getContext('2d');
+ // The page is white and an SVG is transparent; without this the diagram
+ // prints on a black rectangle wherever the canvas started empty.
+ context.fillStyle = '#ffffff';
+ context.fillRect(0, 0, canvas.width, canvas.height);
+ context.drawImage(image, 0, 0, canvas.width, canvas.height);
+ resolve(canvas.toDataURL('image/png').split(',')[1] ?? '');
+ }, { once: true });
+ image.addEventListener(
+ 'error',
+ () => reject(new Error('diagram could not be drawn')),
+ { once: true },
+ );
+ image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
+ });
+}
+
+/**
+ * Draw every pending fence, as `{ key: base64 png }`.
+ *
+ * A diagram that fails to draw is left out rather than failing the export: the
+ * backend prints the fence's own source in its place, which beats losing the
+ * note over one bad diagram.
+ */
+export async function drawDiagrams(pending, { draw = renderMermaidSvg, toPng = rasterise } = {}) {
+ const diagrams = {};
+ for (const { key, source } of pending) {
+ try {
+ const drawn = await draw(source);
+ diagrams[key] = await toPng(drawn.svg, drawn);
+ } catch {
+ // Left to the backend, which keeps the diagram's source visible.
+ }
+ }
+ return diagrams;
+}
+
+/**
+ * Write one PDF per note into the case's exports folder.
+ *
+ * `noteIds` holds note entity ids, and `case` for the case's own scratchpad.
+ * Nothing unsaved travels: the backend reads each note from disk, which is why
+ * the caller flushes a pending edit before calling this.
+ */
+export async function exportNotes(caseId, noteIds, options = {}) {
+ const { diagrams: pending } = await api.post(`/api/cases/${caseId}/notes/pdf/diagrams`, {
+ notes: noteIds,
+ });
+ const diagrams = pending.length ? await drawDiagrams(pending, options) : {};
+ return api.post(`/api/cases/${caseId}/notes/pdf`, { notes: noteIds, diagrams });
+}
+
+export function revealExports(caseId) {
+ return api.post(`/api/cases/${caseId}/notes/pdf/reveal`);
+}
diff --git a/frontend/src/lib/notesExport.test.js b/frontend/src/lib/notesExport.test.js
new file mode 100644
index 0000000..e2232c0
--- /dev/null
+++ b/frontend/src/lib/notesExport.test.js
@@ -0,0 +1,86 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { drawDiagrams, exportNotes, rasterise, revealExports } from './notesExport.js';
+import { api } from './api.js';
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('exporting notes as PDF', () => {
+ it('asks the backend which diagrams to draw, then sends them back', async () => {
+ const post = vi.spyOn(api, 'post').mockImplementation((path) => (
+ path.endsWith('/diagrams')
+ ? Promise.resolve({ diagrams: [{ key: 'abc123', source: 'graph TD; A-->B;' }] })
+ : Promise.resolve({ written: [{ note: 'n1', file: 'Rooftop.pdf' }], warnings: [] })
+ ));
+ const draw = vi.fn(async (source) => ({ svg: `<svg>${source}</svg>`, width: 400, height: 200 }));
+ const toPng = vi.fn(async () => 'AAAA');
+
+ const result = await exportNotes('case-1', ['case', 'n1'], { draw, toPng });
+
+ expect(post).toHaveBeenNthCalledWith(1, '/api/cases/case-1/notes/pdf/diagrams', {
+ notes: ['case', 'n1'],
+ });
+ expect(draw).toHaveBeenCalledWith('graph TD; A-->B;');
+ expect(post).toHaveBeenNthCalledWith(2, '/api/cases/case-1/notes/pdf', {
+ notes: ['case', 'n1'],
+ diagrams: { abc123: 'AAAA' },
+ });
+ expect(result.written).toHaveLength(1);
+ });
+
+ it('skips drawing entirely when no note holds a diagram', async () => {
+ const post = vi.spyOn(api, 'post').mockImplementation((path) => (
+ path.endsWith('/diagrams')
+ ? Promise.resolve({ diagrams: [] })
+ : Promise.resolve({ written: [], warnings: [] })
+ ));
+ const draw = vi.fn();
+
+ await exportNotes('case-1', ['case'], { draw });
+
+ expect(draw).not.toHaveBeenCalled();
+ expect(post).toHaveBeenLastCalledWith('/api/cases/case-1/notes/pdf', {
+ notes: ['case'],
+ diagrams: {},
+ });
+ });
+
+ it('drops a diagram that will not draw rather than losing the export', async () => {
+ const draw = vi.fn()
+ .mockRejectedValueOnce(new Error('bad syntax'))
+ .mockResolvedValueOnce({ svg: '<svg/>', width: 10, height: 10 });
+
+ const diagrams = await drawDiagrams(
+ [{ key: 'broken', source: 'nope' }, { key: 'fine', source: 'graph TD; A-->B;' }],
+ { draw, toPng: async () => 'BBBB' },
+ );
+
+ expect(diagrams).toEqual({ fine: 'BBBB' });
+ });
+
+ it('rasterises a diagram onto an opaque canvas', async () => {
+ const context = { fillRect: vi.fn(), drawImage: vi.fn(), fillStyle: '' };
+ const canvas = { getContext: () => context, toDataURL: () => 'data:image/png;base64,PNGDATA' };
+ vi.stubGlobal('document', { createElement: () => canvas });
+ class FakeImage {
+ addEventListener(type, callback) { if (type === 'load') this.onload = callback; }
+ set src(_value) { queueMicrotask(() => this.onload()); }
+ }
+ vi.stubGlobal('Image', FakeImage);
+
+ await expect(rasterise('<svg/>', { width: 400, height: 200 })).resolves.toBe('PNGDATA');
+ // A transparent SVG on an empty canvas prints black; the fill is what
+ // keeps a diagram on white paper.
+ expect(context.fillStyle).toBe('#ffffff');
+ expect(context.fillRect).toHaveBeenCalled();
+ expect(canvas.width).toBe(800);
+ vi.unstubAllGlobals();
+ });
+
+ it('reveals the export folder without naming a path', async () => {
+ const post = vi.spyOn(api, 'post').mockResolvedValue({ path: '/somewhere/exports' });
+
+ await revealExports('case-1');
+
+ expect(post).toHaveBeenCalledWith('/api/cases/case-1/notes/pdf/reveal');
+ });
+});
diff --git a/frontend/src/tools/Notebook.svelte b/frontend/src/tools/Notebook.svelte
index 32e0d26..aec5a6a 100644
--- a/frontend/src/tools/Notebook.svelte
+++ b/frontend/src/tools/Notebook.svelte
@@ -9,7 +9,8 @@
clampNotebookHelpPosition, clampNotebookSplit, loadNotebookSplit, loadNotebookText,
saveNotebookSplit,
} from '../lib/notebook.js';
- import { downloadNotebookPdf } from '../lib/notebookPdf.js';
+ import { exportNotes, revealExports } from '../lib/notesExport.js';
+ import { destinationLabel, readDestinations } from '../lib/exportDest.js';
import { insertNotebookText, notebookImageMarkdown, notebookMediaMarkdown } from '../lib/notebookContent.js';
import { caseTab, closeNotebookTab, openNotebookTab } from '../lib/notebookTabs.js';
import { openEntity } from '../lib/navigate.js';
@@ -19,6 +20,7 @@
import SearchInput from '../components/SearchInput.svelte';
import FolderBrowser from '../components/FolderBrowser.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
+ import ExportFolderPicker from '../components/ExportFolderPicker.svelte';
import Modal from '../components/Modal.svelte';
import FolderSelect from '../components/FolderSelect.svelte';
@@ -53,6 +55,16 @@
let noteModalSaving = $state(false);
let noteAction = $state(null);
let noteActionBusy = $state(false);
+ let exportOpen = $state(false);
+ let singleExportOpen = $state(false);
+ let singleExportId = $state('case');
+ let exportBusy = $state(false);
+ let exportQuery = $state('');
+ let exportSelection = $state(new Set());
+ // Where the PDFs land, app-wide and remembered. Empty = the case's own
+ // exports folder, so a fresh install exports without being asked anything.
+ let exportDir = $state('');
+ let exportPicker = $state(false);
let text = $state('');
let loadedKey = $state('');
@@ -84,6 +96,17 @@
.filter((entity) => entity.type === 'note')
.sort((a, b) => a.label.localeCompare(b.label)));
const filteredNotes = $derived(noteEntities.filter((entity) => matchesNote(entity, query)));
+ // What the export dialog ticks: the case's own scratchpad first, then every
+ // filed note. The scratchpad has no entity, so it carries the same id the
+ // export route reads it under.
+ const exportChoices = $derived([
+ { id: 'case', label: 'Case notes', folder: '' },
+ ...noteEntities.map((entity) => ({
+ id: entity.id,
+ label: entity.label,
+ folder: entity.attrs?.folder ?? '',
+ })),
+ ].filter((choice) => matchesTerms(`${choice.label} ${choice.folder}`, exportQuery)));
const referenceEntities = $derived(graphEntities
.filter((entity) => entity.provenance?.status !== 'suggested')
.filter((entity) => `${entity.label} ${entity.type}`.toLowerCase().includes(referenceQuery.trim().toLowerCase()))
@@ -372,15 +395,73 @@
saveNotebookSplit(split);
}
- function downloadPdf() {
- // Read the live preview, not the sanitized string: diagrams are drawn into
- // the DOM afterwards and would otherwise print as their source.
- const content = previewEl?.innerHTML ?? preview;
- if (!downloadNotebookPdf({ title, content })) {
- toast('Allow popups to save the PDF.', 'warn');
+ /**
+ * Export a selection of notes, one PDF each, into the notes export folder.
+ *
+ * The backend renders from what is on disk, so a pending edit is flushed
+ * first — otherwise the analyst exports the note as it was 700 ms ago.
+ */
+ async function runExport(noteIds) {
+ if (!caseState.current || exportBusy) return;
+ const caseId = caseState.current.id;
+ exportBusy = true;
+ try {
+ clearTimeout(saveTimer);
+ if (!saved) await save(endpoint, key, text, editVersion);
+ const result = await exportNotes(caseId, noteIds);
+ exportOpen = false;
+ singleExportOpen = false;
+ const count = result.written.length;
+ toast(
+ `${count} PDF${count > 1 ? 's' : ''} written to ${destinationLabel(result.path)}`,
+ 'ok',
+ 5200,
+ {
+ label: 'Show',
+ onClick: () => revealExports(caseId).catch((error) => toast(error.message, 'warn')),
+ },
+ );
+ for (const warning of result.warnings) toast(warning, 'warn', 6500);
+ } catch (error) {
+ toast(`Export failed: ${error.message}`, 'danger');
+ } finally {
+ exportBusy = false;
}
}
+ function readExportDestination() {
+ readDestinations()
+ .then((dirs) => (exportDir = dirs.notes))
+ .catch(() => {});
+ }
+
+ function openCurrentExportDialog() {
+ singleExportId = noteId ?? 'case';
+ singleExportOpen = true;
+ readExportDestination();
+ }
+
+ function openExportDialog() {
+ exportSelection = new Set([noteId ?? 'case']);
+ exportQuery = '';
+ exportOpen = true;
+ closeNotesMenu();
+ // Read it here rather than on mount: the destination only matters once the
+ // analyst is looking at the dialog that shows it.
+ readExportDestination();
+ }
+
+ function toggleExportNote(id) {
+ const next = new Set(exportSelection);
+ if (!next.delete(id)) next.add(id);
+ exportSelection = next;
+ }
+
+ function toggleExportAll() {
+ const all = exportChoices.map((choice) => choice.id);
+ exportSelection = new Set(exportSelection.size === all.length ? [] : all);
+ }
+
function toggleMarkdownHelp() {
markdownHelpOpen = !markdownHelpOpen;
if (markdownHelpOpen) {
@@ -577,9 +658,12 @@
</div>
{/each}
</div>
- <button class="btn btn-ghost btn-sm new-note-button" title="New note" aria-label="New note" onclick={openNewNote}>
+ <button class="btn btn-ghost btn-sm bar-button" title="New note" aria-label="New note" onclick={openNewNote}>
<Icon name="plus" size={15} />
</button>
+ <button class="btn btn-ghost btn-sm bar-button" title="Export several notes as PDF" aria-label="Export several notes as PDF" onclick={openExportDialog}>
+ <Icon name="layers" size={15} />
+ </button>
<div class="bar-actions">
<span class:pending={!saved} class="save-state">{saved ? 'Saved' : saving ? 'Saving…' : 'Unsaved'}</span>
@@ -728,7 +812,7 @@ flowchart LR
</section>
<button class="splitter" aria-label="Resize writer and preview" title="Drag to resize · double-click to reset" onpointerdown={startResize} ondblclick={resetSplit} onkeydown={onSplitterKey}></button>
<article class="pane reader">
- <div class="pane-title"><span>Preview</span><div class="preview-actions"><button class="btn btn-ghost btn-sm" title="Download PDF" aria-label="Download PDF" onclick={downloadPdf}><Icon name="download" size={14} /></button><button class="btn btn-ghost btn-sm preview-toggle" title={previewOnly ? 'Show writer' : 'Preview only'} onclick={() => (previewOnly = !previewOnly)}><Icon name={previewOnly ? 'minimize' : 'maximize'} size={14} /></button></div></div>
+ <div class="pane-title"><span>Preview</span><div class="preview-actions"><button class="btn btn-ghost btn-sm" title="Export this note as PDF" aria-label="Export this note as PDF" disabled={exportBusy} onclick={openCurrentExportDialog}><Icon name="download" size={14} /></button><button class="btn btn-ghost btn-sm preview-toggle" title={previewOnly ? 'Show writer' : 'Preview only'} onclick={() => (previewOnly = !previewOnly)}><Icon name={previewOnly ? 'minimize' : 'maximize'} size={14} /></button></div></div>
<div bind:this={previewEl} class="markdown" aria-label="Markdown preview" use:bindEntityLinks>{@html preview}</div>
</article>
</div>
@@ -750,6 +834,82 @@ flowchart LR
</div>
</Modal>
{/if}
+ {#if singleExportOpen}
+ <Modal title="Export note as PDF" onclose={() => (singleExportOpen = false)} width="560px">
+ <div class="export-dest">
+ <span class="dest-label">Destination</span>
+ <span class="dest-path mono" title={exportDir || "The case's own exports folder"}>
+ {exportDir || "the case's exports folder"}
+ </span>
+ <button class="btn btn-ghost btn-sm" onclick={() => (exportPicker = true)}>Change</button>
+ </div>
+ <p class="export-note">
+ One PDF will be written.
+ {#if exportDir}Files already there are kept.{:else}An existing file with the same name is replaced.{/if}
+ </p>
+ <div class="modal-row">
+ <div style="flex:1"></div>
+ <button class="btn" onclick={() => (singleExportOpen = false)}>Cancel</button>
+ <button class="btn btn-primary" disabled={exportBusy} onclick={() => runExport([singleExportId])}>
+ {exportBusy ? 'Exporting…' : 'Export PDF'}
+ </button>
+ </div>
+ </Modal>
+ {/if}
+ {#if exportOpen}
+ <Modal title="Export notes as PDF" onclose={() => (exportOpen = false)} width="560px">
+ {#if exportChoices.length > NOTE_SEARCH_MIN}
+ <SearchInput bind:value={exportQuery} placeholder="Find a note…" />
+ {/if}
+ <div class="export-list">
+ {#each exportChoices as choice (choice.id)}
+ <label class="export-row">
+ <input
+ type="checkbox"
+ checked={exportSelection.has(choice.id)}
+ onchange={() => toggleExportNote(choice.id)}
+ />
+ <span class="export-name">{choice.label}</span>
+ {#if choice.folder}<small>{choice.folder}</small>{/if}
+ </label>
+ {/each}
+ {#if !exportChoices.length}<p class="export-empty">No matching notes.</p>{/if}
+ </div>
+ <div class="export-dest">
+ <span class="dest-label">Destination</span>
+ <span class="dest-path mono" title={exportDir || "The case's own exports folder"}>
+ {exportDir || "the case's exports folder"}
+ </span>
+ <button class="btn btn-ghost btn-sm" onclick={() => (exportPicker = true)}>Change</button>
+ </div>
+ <p class="export-note">
+ One PDF per note.
+ {#if exportDir}Files already there are kept.{:else}Existing files are replaced.{/if}
+ </p>
+ <div class="modal-row">
+ <button class="btn btn-ghost btn-sm" onclick={toggleExportAll}>
+ {exportSelection.size === exportChoices.length ? 'Clear' : 'Select all'}
+ </button>
+ <div style="flex:1"></div>
+ <button class="btn" onclick={() => (exportOpen = false)}>Cancel</button>
+ <button
+ class="btn btn-primary"
+ disabled={exportBusy || !exportSelection.size}
+ onclick={() => runExport([...exportSelection])}
+ >
+ {exportBusy ? 'Exporting…' : `Export ${exportSelection.size || ''}`}
+ </button>
+ </div>
+ </Modal>
+ {/if}
+ {#if exportPicker}
+ <ExportFolderPicker
+ kind="notes"
+ current={exportDir}
+ onclose={() => (exportPicker = false)}
+ onchosen={(path) => (exportDir = path)}
+ />
+ {/if}
{#if noteAction}
<ConfirmDialog
title={noteAction.kind === 'delete' ? 'Delete this note?' : 'Reset note content?'}
@@ -788,8 +948,8 @@ flowchart LR
.menu-empty { margin: 8px; color: var(--text-3); font-size: var(--fs-sm); }
.tabs { flex: 1; min-width: 0; display: flex; align-items: stretch; overflow-x: auto; scrollbar-width: none; }
.tabs::-webkit-scrollbar { display: none; }
- .new-note-button { flex-shrink: 0; align-self: center; color: var(--text-2); }
- .new-note-button:hover { color: var(--accent); }
+ .bar-button { flex-shrink: 0; align-self: center; color: var(--text-2); }
+ .bar-button:hover { color: var(--accent); }
.tab { display: flex; align-items: center; max-width: 180px; color: var(--text-3); border-bottom: 2px solid transparent; font-size: var(--fs-sm); white-space: nowrap; }
.tab:hover { color: var(--text-1); background: var(--bg-2); }
.tab.active { color: var(--text-1); border-bottom-color: var(--accent); }
@@ -868,6 +1028,16 @@ flowchart LR
.reference-row small { color: var(--text-3); font-size: var(--fs-xs); }
.preview-toggle { margin: -6px -7px -6px 0; }
.preview-actions { display: flex; align-items: center; gap: 2px; }
+ .export-list { max-height: 46vh; margin: 10px 0 0; overflow-y: auto; }
+ .export-row { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 8px; padding: 7px; border-radius: var(--r-sm); color: var(--text-2); font-size: var(--fs-sm); cursor: pointer; }
+ .export-row:hover { background: var(--bg-2); color: var(--text-1); }
+ .export-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .export-row small { color: var(--text-3); font-size: var(--fs-xs); }
+ .export-empty { padding: 14px 7px; color: var(--text-3); font-size: var(--fs-sm); }
+ .export-note { margin: 6px 0 0; color: var(--text-3); font-size: var(--fs-xs); }
+ .export-dest { display: flex; align-items: center; gap: 8px; margin-top: 10px; }
+ .dest-label { color: var(--text-3); font-size: var(--fs-xs); }
+ .dest-path { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--fs-xs); }
/* The shared rendered-Markdown rules live in app.css; what follows is what
only the Notebook preview shows. */
.markdown { margin-top: 10px; }
diff --git a/frontend/src/tools/Notebook.test.js b/frontend/src/tools/Notebook.test.js
index 00cbe79..a1b4958 100644
--- a/frontend/src/tools/Notebook.test.js
+++ b/frontend/src/tools/Notebook.test.js
@@ -55,13 +55,25 @@ describe('Notebook note creation', () => {
expect(body).not.toContain('aria-label="Delete note"');
});
- it('places PDF download beside the preview-only control', () => {
+ it('offers both PDF exports beside the preview-only control', () => {
caseState.current = { id: 'case-1', entities: [] };
const { body } = render(Notebook);
- expect(body).toContain('aria-label="Download PDF"');
- expect(body.indexOf('aria-label="Download PDF"')).toBeLessThan(body.indexOf('title="Preview only"'));
+ // The open note has its own destination dialog; another dialog selects several.
+ expect(body).toContain('aria-label="Export this note as PDF"');
+ expect(body).toContain('aria-label="Export several notes as PDF"');
+ expect(body.indexOf('aria-label="Export this note as PDF"'))
+ .toBeLessThan(body.indexOf('title="Preview only"'));
+ });
+
+ it('opens a destination dialog before exporting the current note', () => {
+ expect(source).toContain('onclick={openCurrentExportDialog}');
+ expect(source).toContain('<Modal title="Export note as PDF"');
+ expect(source).toContain('singleExportId = noteId ?? \'case\';');
+ expect(source).toContain('onclick={() => (exportPicker = true)}>Change</button>');
+ expect(source).toContain('onclick={() => runExport([singleExportId])}');
+ expect(source).toContain("{exportBusy ? 'Exporting…' : 'Export PDF'}");
});
});
diff --git a/packaging/azimut.spec b/packaging/azimut.spec
index c7e8f7a..5ced704 100644
--- a/packaging/azimut.spec
+++ b/packaging/azimut.spec
@@ -19,6 +19,11 @@ hiddenimports = (
+ collect_submodules("azimut")
+ collect_submodules("yt_dlp")
+ collect_submodules("gallery_dl")
+ # fontTools loads a TrueType table's converter by looking up a module named
+ # after the tag it just read, so nothing imports those modules by name and
+ # PyInstaller cannot see them. Without this the notes PDF would fail in the
+ # frozen binary only, on the first font fpdf2 subsets.
+ + collect_submodules("fontTools")
)
# Linux only: yt-dlp reaches for these lazily to unseal a Chromium-family
@@ -33,7 +38,12 @@ if sys.platform == "linux":
+ ["cryptography"]
)
-# Grabs azimut/static/** (index.html, assets, favicon) from the installed package.
+# Grabs the package's data files from the installed wheel: azimut/static/**
+# (index.html, assets, favicon) and azimut/assets/fonts/** — the 15 MB of Noto,
+# Droid and DejaVu faces the notes PDF draws with (engine/pdffonts.py). The
+# fonts have to be in the bundle, not on the machine: a PDF embeds the glyphs it
+# uses, so an export made on Windows and one made on Linux must find the same
+# faces or they are different documents.
datas = collect_data_files("azimut")
# The IANA timezone database, which `zoneinfo` falls back to when the OS has none
diff --git a/pyproject.toml b/pyproject.toml
index 84629c7..9c60549 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -37,6 +37,20 @@ dependencies = [
"numpy>=1.26,<3",
"requests>=2.31,<3",
"python-multipart>=0.0.9,<1.0",
+ # Notes to PDF (engine/notes_pdf.py). fpdf2 and markdown-it-py are pure
+ # Python, so the three binaries get the same renderer and no build step.
+ # WeasyPrint would render nicer CSS but needs Pango and cairo present on the
+ # machine, which is a GTK install on Windows and the end of the one-click
+ # binary. reportlab was tried and dropped: it cannot draw Burmese and Arabic
+ # correctly in one document (see docs, and the shaping note below).
+ "fpdf2>=2.8,<3",
+ "markdown-it-py>=4.0,<5",
+ # Text shaping, and not optional: without it Arabic comes out unjoined and
+ # Burmese mis-stacked — text that looks like text and is wrong, which is
+ # worse than text that is missing. fpdf2 uses it when it is importable,
+ # which is why nothing imports it by name. abi3 wheels cover win_amd64,
+ # macOS universal2 and manylinux x86_64/arm64.
+ "uharfbuzz>=0.50,<1",
# Timezone from a latitude/longitude, for the civil local time the sun and
# moon panel shows beside UTC (engine/sky.py). Chosen over timezonefinder,
# which carries 65 MB of tz polygons into each of the three binaries where
@@ -73,6 +87,9 @@ dev = [
# Starlette 1.3+ uses HTTPX2 for TestClient; keep the old HTTPX runtime
# client above because application integrations still import that package.
"httpx2>=2,<3",
+ # Reads an exported note back, so the PDF tests assert what is on the page
+ # rather than that bytes were written. Test-only: nothing ships it.
+ "pypdf>=6,<7",
# Static analysis, run in CI (see .github/workflows/ci.yml). ruff is 0.x and
# ships rule changes between minors, so it's pinned to one minor; mypy to the
# next major. Both bounds are raised deliberately, after the suite is green.
diff --git a/src/azimut/api/cases.py b/src/azimut/api/cases.py
index 2df4c70..fca7ff0 100644
--- a/src/azimut/api/cases.py
+++ b/src/azimut/api/cases.py
@@ -1,4 +1,7 @@
-"""REST API for case lifecycle, notes, entities and links."""
+"""REST API for case lifecycle, entities and links.
+
+The note bodies and their PDF export live next door in `api/notes.py`.
+"""
from __future__ import annotations
@@ -154,16 +157,6 @@ class PromoteCase(BaseModel):
name: str = Field(min_length=1, max_length=120)
-class Notes(BaseModel):
- text: str
-
-
-class NoteIn(BaseModel):
- title: str = Field(min_length=1, max_length=300)
- folder: str = Field(default="", max_length=120)
- content: str = ""
-
-
class EntityIn(BaseModel):
type: str = Field(min_length=1, max_length=40)
label: str = Field(min_length=1, max_length=300)
@@ -173,7 +166,7 @@ class EntityIn(BaseModel):
class EntityPatch(BaseModel):
type: str | None = None
- label: str | None = None
+ label: str | None = Field(default=None, min_length=1, max_length=300)
attrs: dict[str, Any] | None = None
status: EntityStatus | None = None
@@ -478,39 +471,6 @@ def download_bundle(case_id: str, job_id: str) -> FileResponse:
)
[email protected]("/{case_id}/notes")
-def read_notes(case_id: str) -> dict[str, str]:
- return {"text": get_case(case_id).read_notes()}
-
-
[email protected]("/{case_id}/notes")
-def write_notes(case_id: str, body: Notes) -> dict[str, str]:
- get_case(case_id).write_notes(body.text)
- return {"status": "saved"}
-
-
[email protected]("/{case_id}/notes")
-def create_note(case_id: str, body: NoteIn) -> dict[str, Any]:
- return get_case(case_id).create_note(body.title.strip(), body.folder.strip(), body.content)
-
-
[email protected]("/{case_id}/notes/{note_id}")
-def read_note(case_id: str, note_id: str) -> dict[str, str]:
- try:
- return {"text": get_case(case_id).read_note(note_id)}
- except CaseError as exc:
- raise HTTPException(status_code=404, detail=str(exc)) from exc
-
-
[email protected]("/{case_id}/notes/{note_id}")
-def write_note(case_id: str, note_id: str, body: Notes) -> dict[str, str]:
- try:
- get_case(case_id).write_note(note_id, body.text)
- except CaseError as exc:
- raise HTTPException(status_code=404, detail=str(exc)) from exc
- return {"status": "saved"}
-
-
@router.get("/{case_id}/catalog/entities")
def catalog_entities(
case_id: str,
diff --git a/src/azimut/api/notes.py b/src/azimut/api/notes.py
new file mode 100644
index 0000000..8e80012
--- /dev/null
+++ b/src/azimut/api/notes.py
@@ -0,0 +1,245 @@
+"""REST API for the notebook: note bodies, and exporting them to PDF.
+
+The case scratchpad and the filed notes are read and written here. So is the
+export, which is the reason this left `api/cases.py`: turning a note into a
+document is a surface of its own — a payload to bound, a renderer to drive and
+files to write into the case's export folder.
+
+An export writes one PDF per note, named after the note, into the folder the
+analyst chose for notes — the case's own `exports/` until they pick another one
+(`engine/exportdir.py`). Names follow the same rule as an imported media's
+(`layout.visible_filename`).
+
+Inside the case, a re-export overwrites: that folder is meant to be refreshed in
+one click, not to accumulate `note (2).pdf`. In a folder of the analyst's own it
+never overwrites, because the files there are theirs.
+"""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import hashlib
+from typing import Any
+
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel, Field
+
+from .. import layout
+from ..engine import exportdir
+from ..engine import notes_pdf as pdf_engine
+from ..engine import pdffonts
+from ..engine import reveal as reveal_engine
+from ..workspace import Case, CaseError
+from .cases import get_case
+
+router = APIRouter(prefix="/api/cases", tags=["notes"])
+
+#: The case's own scratchpad, which is a note without an entity behind it.
+CASE_NOTE = "case"
+#: Where the PDFs land, until the case can point somewhere of its own.
+EXPORTS_DIR = "exports"
+
+#: Bounds on one export request. Generous enough for a whole case, small enough
+#: that a single call cannot ask the machine to lay out a library.
+MAX_NOTES = 200
+MAX_DIAGRAMS = 120
+MAX_DIAGRAM_BYTES = 4_000_000
+MAX_DIAGRAM_TOTAL_BYTES = 16_000_000
+#: JSON + base64 overhead above the decoded batch limit. Enforced by an ASGI
+#: receive wrapper before Pydantic materialises the request.
+MAX_PDF_BODY_BYTES = 24_000_000
+
+
+class Notes(BaseModel):
+ text: str
+
+
+class NoteIn(BaseModel):
+ title: str = Field(min_length=1, max_length=300)
+ folder: str = Field(default="", max_length=120)
+ content: str = ""
+
+
+class NoteSelection(BaseModel):
+ notes: list[str] = Field(min_length=1, max_length=MAX_NOTES)
+
+
+class ExportIn(NoteSelection):
+ """Which notes to export, and the diagrams the browser drew for them.
+
+ Mermaid needs a browser, so the caller asks which fences a selection holds
+ (`/notes/pdf/diagrams`), draws them, and posts each one back as a PNG under
+ the key it was given. One map serves every note in the request: two notes
+ holding the same diagram upload it once.
+ """
+
+ diagrams: dict[str, str] = Field(default_factory=dict)
+
+
[email protected]("/{case_id}/notes")
+def read_notes(case_id: str) -> dict[str, str]:
+ return {"text": get_case(case_id).read_notes()}
+
+
[email protected]("/{case_id}/notes")
+def write_notes(case_id: str, body: Notes) -> dict[str, str]:
+ get_case(case_id).write_notes(body.text)
+ return {"status": "saved"}
+
+
[email protected]("/{case_id}/notes")
+def create_note(case_id: str, body: NoteIn) -> dict[str, Any]:
+ return get_case(case_id).create_note(body.title.strip(), body.folder.strip(), body.content)
+
+
[email protected]("/{case_id}/notes/{note_id}")
+def read_note(case_id: str, note_id: str) -> dict[str, str]:
+ try:
+ return {"text": get_case(case_id).read_note(note_id)}
+ except CaseError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+
+
[email protected]("/{case_id}/notes/{note_id}")
+def write_note(case_id: str, note_id: str, body: Notes) -> dict[str, str]:
+ try:
+ get_case(case_id).write_note(note_id, body.text)
+ except CaseError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ return {"status": "saved"}
+
+
+def _decode_diagrams(encoded: dict[str, str]) -> dict[str, bytes]:
+ """Decode the whole batch before a single page is laid out."""
+ if len(encoded) > MAX_DIAGRAMS:
+ raise HTTPException(
+ status_code=422, detail=f"an export carries at most {MAX_DIAGRAMS} diagrams"
+ )
+ decoded: dict[str, bytes] = {}
+ total_bytes = 0
+ for key, payload in encoded.items():
+ if not key or len(key) > 64 or not key.isalnum():
+ raise HTTPException(status_code=422, detail="invalid diagram key")
+ try:
+ data = base64.b64decode(payload, validate=True)
+ except (binascii.Error, ValueError) as exc:
+ raise HTTPException(status_code=422, detail="invalid diagram payload") from exc
+ if not data or len(data) > MAX_DIAGRAM_BYTES:
+ raise HTTPException(status_code=422, detail="diagram image too large")
+ total_bytes += len(data)
+ if total_bytes > MAX_DIAGRAM_TOTAL_BYTES:
+ raise HTTPException(status_code=422, detail="diagram batch too large")
+ decoded[key] = data
+ return decoded
+
+
+def _note_source(case: Case, note_id: str) -> tuple[str, str]:
+ """The title and Markdown of one note, scratchpad included."""
+ if note_id == CASE_NOTE:
+ return "Case notes", case.read_notes()
+ entity = case.get_entity(note_id)
+ if entity is None or entity.get("type") != "note":
+ raise HTTPException(status_code=404, detail=f"note '{note_id}' not found")
+ return str(entity.get("label") or "Note"), case.read_note(note_id)
+
+
+def _pdf_filename(title: str, note_id: str, peers: dict[str, list[str]]) -> str:
+ """A stable flat filename, keeping a homonym marker after truncation."""
+ if len(peers.get(title.casefold(), [])) < 2:
+ return layout.visible_filename(title, ".pdf")
+ token = hashlib.sha256(note_id.encode("utf-8")).hexdigest()[:16]
+ marker = f" [{token}]"
+ stem_limit = max(1, layout.MAX_MEDIA_NAME - len(".pdf") - len(marker))
+ stem = layout.slugify(title, "Note", limit=stem_limit)
+ return f"{stem}{marker}.pdf"
+
+
[email protected]("/{case_id}/notes/pdf/diagrams")
+def export_diagrams(case_id: str, body: NoteSelection) -> dict[str, Any]:
+ """The Mermaid fences a selection holds, for the browser to draw.
+
+ The browser could look for them itself, but then two parsers would decide
+ what counts as a diagram and they would drift. This way the notes are read
+ once, on the side that renders them, and the answer is deduplicated: the
+ same diagram in four notes is drawn once.
+ """
+ case = get_case(case_id)
+ fences: dict[str, str] = {}
+ for note_id in dict.fromkeys(body.notes):
+ _, text = _note_source(case, note_id)
+ for source in pdf_engine.mermaid_sources(text):
+ fences.setdefault(pdf_engine.diagram_key(source), source)
+ pending = list(fences.items())[:MAX_DIAGRAMS]
+ return {"diagrams": [{"key": key, "source": source} for key, source in pending]}
+
+
[email protected]("/{case_id}/notes/pdf")
+def export_pdf(case_id: str, body: ExportIn) -> dict[str, Any]:
+ """Write one PDF per requested note into the notes export folder."""
+ case = get_case(case_id)
+ diagrams = _decode_diagrams(body.diagrams)
+ try:
+ destination = exportdir.destination("notes", case.path)
+ except exportdir.ExportDirError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ in_case = destination == layout.subdir(case.path, EXPORTS_DIR)
+
+ selected = [
+ (note_id, *_note_source(case, note_id)) for note_id in dict.fromkeys(body.notes)
+ ]
+ peers = case.note_ids_by_titles({title for _, title, _ in selected})
+ peers.setdefault("case notes", []).append(CASE_NOTE)
+
+ written: list[dict[str, str]] = []
+ warnings: list[str] = []
+ for note_id, title, text in selected:
+ try:
+ rendered = pdf_engine.render(case, title=title, text=text, diagrams=diagrams)
+ except pdffonts.FontError as exc:
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
+ except pdf_engine.NotesPdfError as exc:
+ # One unlayoutable note must not lose the rest of the batch.
+ warnings.append(f"{title}: {exc}")
+ continue
+ filename = _pdf_filename(title, note_id, peers)
+ try:
+ if in_case:
+ path = destination / filename
+ path.write_bytes(rendered.pdf)
+ else:
+ path = exportdir.write_out(rendered.pdf, destination, filename)
+ except (OSError, exportdir.ExportDirError) as exc:
+ raise HTTPException(status_code=409, detail=f"could not write the PDF: {exc}") from exc
+ written.append({"note": note_id, "title": title, "file": path.name})
+ warnings.extend(f"{title}: {warning}" for warning in rendered.warnings)
+
+ if not written:
+ raise HTTPException(status_code=422, detail="; ".join(warnings) or "nothing to export")
+ return {
+ "written": written,
+ "warnings": warnings,
+ "folder": EXPORTS_DIR if in_case else str(destination),
+ "path": str(destination),
+ }
+
+
[email protected]("/{case_id}/notes/pdf/reveal")
+def reveal_exports(case_id: str) -> dict[str, str]:
+ """Open the folder the PDFs were written to, in the system file manager.
+
+ Takes no path: the case id and the saved notes destination are enough to find
+ the folder, so nothing the browser sends can point somewhere else. That saved
+ folder is allowed to be outside the workspace, which is the whole point of
+ choosing one.
+ """
+ case = get_case(case_id)
+ try:
+ destination = exportdir.destination("notes", case.path)
+ except exportdir.ExportDirError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ try:
+ reveal_engine.reveal(destination, workspace_only=False)
+ except reveal_engine.RevealError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ return {"path": str(destination)}
diff --git a/src/azimut/assets/fonts/APACHE-2.0.txt b/src/azimut/assets/fonts/APACHE-2.0.txt
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/src/azimut/assets/fonts/APACHE-2.0.txt
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/src/azimut/assets/fonts/BITSTREAM-VERA.txt b/src/azimut/assets/fonts/BITSTREAM-VERA.txt
new file mode 100644
index 0000000..b3d93a1
--- /dev/null
+++ b/src/azimut/assets/fonts/BITSTREAM-VERA.txt
@@ -0,0 +1,78 @@
+Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
+Upstream-Name: DejaVu fonts
+Upstream-Author: Stepan Roh <[email protected]> (original author),
+ see /usr/share/doc/fonts-dejavu-core/AUTHORS for full list
+Source: https://dejavu-fonts.github.io/
+
+Files: *
+Copyright: Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved.
+ Bitstream Vera is a trademark of Bitstream, Inc.
+ DejaVu changes are in public domain.
+License: bitstream-vera
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of the fonts accompanying this license ("Fonts") and associated
+ documentation files (the "Font Software"), to reproduce and distribute the
+ Font Software, including without limitation the rights to use, copy, merge,
+ publish, distribute, and/or sell copies of the Font Software, and to permit
+ persons to whom the Font Software is furnished to do so, subject to the
+ following conditions:
+ .
+ The above copyright and trademark notices and this permission notice shall
+ be included in all copies of one or more of the Font Software typefaces.
+ .
+ The Font Software may be modified, altered, or added to, and in particular
+ the designs of glyphs or characters in the Fonts may be modified and
+ additional glyphs or characters may be added to the Fonts, only if the fonts
+ are renamed to names not containing either the words "Bitstream" or the word
+ "Vera".
+ .
+ This License becomes null and void to the extent applicable to Fonts or Font
+ Software that has been modified and is distributed under the "Bitstream
+ Vera" names.
+ .
+ The Font Software may be sold as part of a larger software package but no
+ copy of one or more of the Font Software typefaces may be sold by itself.
+ .
+ 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 BITSTREAM OR THE GNOME
+ FOUNDATION 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.
+ .
+ Except as contained in this notice, the names of Gnome, the Gnome
+ Foundation, and Bitstream Inc., shall not be used in advertising or
+ otherwise to promote the sale, use or other dealings in this Font Software
+ without prior written authorization from the Gnome Foundation or Bitstream
+ Inc., respectively. For further information, contact: fonts at gnome dot
+ org.
+
+Files: debian/*
+Copyright: (C) 2005-2006 Peter Cernak <[email protected]>
+ (C) 2006-2011 Davide Viti <[email protected]>
+ (C) 2011-2013 Christian Perrier <[email protected]>
+ (C) 2013 Fabian Greffrath <[email protected]>
+License: GPL-2+
+ This program is free software; you can redistribute it
+ and/or modify it under the terms of the GNU General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later
+ version.
+ .
+ This program is distributed in the hope that it will be
+ useful, but WITHOUT ANY WARRANTY; without even the implied
+ warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ PURPOSE. See the GNU General Public License for more
+ details.
+ .
+ You should have received a copy of the GNU General Public
+ License along with this package; if not, write to the Free
+ Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ Boston, MA 02110-1301 USA
+ .
+ On Debian systems, the full text of the GNU General Public
+ License version 2 can be found in the file
+ /usr/share/common-licenses/GPL-2'.
diff --git a/src/azimut/assets/fonts/DejaVuSans.ttf b/src/azimut/assets/fonts/DejaVuSans.ttf
new file mode 100644
index 0000000..fb0bd94
Binary files /dev/null and b/src/azimut/assets/fonts/DejaVuSans.ttf differ
diff --git a/src/azimut/assets/fonts/DroidSansFallbackFull.ttf b/src/azimut/assets/fonts/DroidSansFallbackFull.ttf
new file mode 100644
index 0000000..89959f5
Binary files /dev/null and b/src/azimut/assets/fonts/DroidSansFallbackFull.ttf differ
diff --git a/src/azimut/assets/fonts/NanumGothic-Regular.ttf b/src/azimut/assets/fonts/NanumGothic-Regular.ttf
new file mode 100644
index 0000000..2aa2b20
Binary files /dev/null and b/src/azimut/assets/fonts/NanumGothic-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSans-Bold.ttf b/src/azimut/assets/fonts/NotoSans-Bold.ttf
new file mode 100644
index 0000000..4d923cb
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSans-Bold.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSans-Regular.ttf b/src/azimut/assets/fonts/NotoSans-Regular.ttf
new file mode 100644
index 0000000..7e9c169
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSans-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansAdlam-Regular.ttf b/src/azimut/assets/fonts/NotoSansAdlam-Regular.ttf
new file mode 100644
index 0000000..73517cf
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansAdlam-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansArabic-Regular.ttf b/src/azimut/assets/fonts/NotoSansArabic-Regular.ttf
new file mode 100644
index 0000000..a3c66dc
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansArabic-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansArmenian-Regular.ttf b/src/azimut/assets/fonts/NotoSansArmenian-Regular.ttf
new file mode 100644
index 0000000..b516c64
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansArmenian-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansBalinese-Regular.ttf b/src/azimut/assets/fonts/NotoSansBalinese-Regular.ttf
new file mode 100644
index 0000000..8a7ee2b
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansBalinese-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansBengali-Regular.ttf b/src/azimut/assets/fonts/NotoSansBengali-Regular.ttf
new file mode 100644
index 0000000..32a1397
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansBengali-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansCanadianAboriginal-Regular.ttf b/src/azimut/assets/fonts/NotoSansCanadianAboriginal-Regular.ttf
new file mode 100644
index 0000000..b43c475
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansCanadianAboriginal-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansCham-Regular.ttf b/src/azimut/assets/fonts/NotoSansCham-Regular.ttf
new file mode 100644
index 0000000..28d0a53
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansCham-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansCherokee-Regular.ttf b/src/azimut/assets/fonts/NotoSansCherokee-Regular.ttf
new file mode 100644
index 0000000..5440492
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansCherokee-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansCoptic-Regular.ttf b/src/azimut/assets/fonts/NotoSansCoptic-Regular.ttf
new file mode 100644
index 0000000..34667d3
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansCoptic-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansDevanagari-Regular.ttf b/src/azimut/assets/fonts/NotoSansDevanagari-Regular.ttf
new file mode 100644
index 0000000..cb4957a
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansDevanagari-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansEthiopic-Regular.ttf b/src/azimut/assets/fonts/NotoSansEthiopic-Regular.ttf
new file mode 100644
index 0000000..de3a949
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansEthiopic-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansGeorgian-Regular.ttf b/src/azimut/assets/fonts/NotoSansGeorgian-Regular.ttf
new file mode 100644
index 0000000..aa6e93e
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansGeorgian-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansGujarati-Regular.ttf b/src/azimut/assets/fonts/NotoSansGujarati-Regular.ttf
new file mode 100644
index 0000000..64a8ded
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansGujarati-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansGurmukhi-Regular.ttf b/src/azimut/assets/fonts/NotoSansGurmukhi-Regular.ttf
new file mode 100644
index 0000000..6033bc9
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansGurmukhi-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansHebrew-Regular.ttf b/src/azimut/assets/fonts/NotoSansHebrew-Regular.ttf
new file mode 100644
index 0000000..493b7d2
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansHebrew-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansJavanese-Regular.ttf b/src/azimut/assets/fonts/NotoSansJavanese-Regular.ttf
new file mode 100644
index 0000000..b122eb2
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansJavanese-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansKannada-Regular.ttf b/src/azimut/assets/fonts/NotoSansKannada-Regular.ttf
new file mode 100644
index 0000000..9547349
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansKannada-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansKhmer-Regular.ttf b/src/azimut/assets/fonts/NotoSansKhmer-Regular.ttf
new file mode 100644
index 0000000..c24a97e
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansKhmer-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansLao-Regular.ttf b/src/azimut/assets/fonts/NotoSansLao-Regular.ttf
new file mode 100644
index 0000000..58dbe24
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansLao-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansMalayalam-Regular.ttf b/src/azimut/assets/fonts/NotoSansMalayalam-Regular.ttf
new file mode 100644
index 0000000..1f4d4b0
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansMalayalam-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansMongolian-Regular.ttf b/src/azimut/assets/fonts/NotoSansMongolian-Regular.ttf
new file mode 100644
index 0000000..d452232
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansMongolian-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansMono-Regular.ttf b/src/azimut/assets/fonts/NotoSansMono-Regular.ttf
new file mode 100644
index 0000000..dd3e6d0
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansMono-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansMyanmar-Regular.ttf b/src/azimut/assets/fonts/NotoSansMyanmar-Regular.ttf
new file mode 100644
index 0000000..5aefed2
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansMyanmar-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansNKo-Regular.ttf b/src/azimut/assets/fonts/NotoSansNKo-Regular.ttf
new file mode 100644
index 0000000..a6aa2ed
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansNKo-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansOriya-Regular.ttf b/src/azimut/assets/fonts/NotoSansOriya-Regular.ttf
new file mode 100644
index 0000000..06f2c8f
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansOriya-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansSinhala-Regular.ttf b/src/azimut/assets/fonts/NotoSansSinhala-Regular.ttf
new file mode 100644
index 0000000..e8f10b4
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansSinhala-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansSyriac-Regular.ttf b/src/azimut/assets/fonts/NotoSansSyriac-Regular.ttf
new file mode 100644
index 0000000..6d837db
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansSyriac-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansTamil-Regular.ttf b/src/azimut/assets/fonts/NotoSansTamil-Regular.ttf
new file mode 100644
index 0000000..d4f6114
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansTamil-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansTelugu-Regular.ttf b/src/azimut/assets/fonts/NotoSansTelugu-Regular.ttf
new file mode 100644
index 0000000..e67159e
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansTelugu-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansThaana-Regular.ttf b/src/azimut/assets/fonts/NotoSansThaana-Regular.ttf
new file mode 100644
index 0000000..f600997
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansThaana-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansThai-Regular.ttf b/src/azimut/assets/fonts/NotoSansThai-Regular.ttf
new file mode 100644
index 0000000..de76860
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansThai-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansTifinagh-Regular.ttf b/src/azimut/assets/fonts/NotoSansTifinagh-Regular.ttf
new file mode 100644
index 0000000..9601b5b
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansTifinagh-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansVai-Regular.ttf b/src/azimut/assets/fonts/NotoSansVai-Regular.ttf
new file mode 100644
index 0000000..a722f3a
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansVai-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSansYi-Regular.ttf b/src/azimut/assets/fonts/NotoSansYi-Regular.ttf
new file mode 100644
index 0000000..36bbbce
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSansYi-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSerif-Bold.ttf b/src/azimut/assets/fonts/NotoSerif-Bold.ttf
new file mode 100644
index 0000000..ac3ef19
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSerif-Bold.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSerif-BoldItalic.ttf b/src/azimut/assets/fonts/NotoSerif-BoldItalic.ttf
new file mode 100644
index 0000000..a4e13e6
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSerif-BoldItalic.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSerif-Italic.ttf b/src/azimut/assets/fonts/NotoSerif-Italic.ttf
new file mode 100644
index 0000000..cd23dcc
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSerif-Italic.ttf differ
diff --git a/src/azimut/assets/fonts/NotoSerif-Regular.ttf b/src/azimut/assets/fonts/NotoSerif-Regular.ttf
new file mode 100644
index 0000000..c3bcfe6
Binary files /dev/null and b/src/azimut/assets/fonts/NotoSerif-Regular.ttf differ
diff --git a/src/azimut/assets/fonts/OFL.txt b/src/azimut/assets/fonts/OFL.txt
new file mode 100644
index 0000000..b2542cb
--- /dev/null
+++ b/src/azimut/assets/fonts/OFL.txt
@@ -0,0 +1,116 @@
+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.
+
+License: GPL-3+
+License-Reference: /usr/share/common-licenses/GPL-3
diff --git a/src/azimut/assets/fonts/README.md b/src/azimut/assets/fonts/README.md
new file mode 100644
index 0000000..f236dc1
--- /dev/null
+++ b/src/azimut/assets/fonts/README.md
@@ -0,0 +1,36 @@
+# Fonts shipped with the notes PDF export
+
+A PDF embeds the faces it draws with, so `engine/notes_pdf.py` cannot use
+whatever the machine has installed: the same note must come out the same from
+the Windows, Linux and macOS binaries. These faces ship in the wheel and in the
+frozen binaries (`packaging/azimut.spec`), and only the glyphs a document uses
+are embedded in it — a note with three Burmese words does not carry the Burmese
+font.
+
+| File | Drawn as | Covers |
+|---|---|---|
+| `NotoSerif-Regular/Bold/Italic/BoldItalic` | body text | Latin, Greek, Cyrillic |
+| `NotoSans-Regular/Bold` | headings, tables, footer | Latin, Greek, Cyrillic |
+| `NotoSansMono-Regular` | code | Latin, Greek, Cyrillic |
+| `DroidSansFallbackFull` | fallback | Chinese, Japanese |
+| `NanumGothic-Regular` | fallback | Korean |
+| `NotoSans<Script>-Regular` × 28 | fallback | Arabic, Hebrew, Burmese, Thai, the Indic scripts, Georgian, Armenian, Ethiopic, Khmer, Lao and the rest of the living scripts |
+| `DejaVuSans` | fallback | arrows, ticks, box drawing, degree signs |
+
+About 15 MB in total, 7 MB of it compressed into the wheel. Which face draws
+which range is declared once, in `engine/pdffonts.py`'s `SCRIPTS` table, and
+`tests/test_notes_pdf.py` fails if a file named there is missing — or if a file
+here is named nowhere.
+
+Nothing is borrowed from the machine, including CJK: a note exported on Windows
+and the same note exported on Linux have to be the same document, and a font
+that is only sometimes installed cannot promise that.
+
+Arabic, Burmese and the Indic scripts need their letters joined, stacked and
+reordered, which fpdf2 does through HarfBuzz (`uharfbuzz`, a hard dependency for
+that reason).
+
+Licences: the Noto faces and Nanum Gothic are SIL Open Font License 1.1
+(`OFL.txt`), Droid Sans Fallback is Apache 2.0 (`APACHE-2.0.txt`), and DejaVu is
+the Bitstream Vera / Arev licence (`BITSTREAM-VERA.txt`). All are
+redistributable, and all require their licence to travel with the files.
diff --git a/src/azimut/engine/notes_pdf.py b/src/azimut/engine/notes_pdf.py
new file mode 100644
index 0000000..6e00290
--- /dev/null
+++ b/src/azimut/engine/notes_pdf.py
@@ -0,0 +1,954 @@
+"""A note rendered to PDF, server-side.
+
+The notebook used to export by opening a print window and handing the browser a
+stylesheet. That put the result in Chrome's hands: a popup blocker could stop
+it, the print dialog added its own margins and page furniture, images sometimes
+printed half-loaded, and nothing could produce more than the one note on screen.
+
+So the PDF is built here instead, from the Markdown source rather than from the
+preview's DOM. `markdown-it-py` parses the same dialect the preview does — the
+source goes through the same rewrites `lib/markdown.js` applies (`[[entity:…]]`,
+`[[media:…]]`, `![…](…){width=…}`, `::: center` blocks) so a note reads the same
+in both places — and fpdf2 lays the page out.
+
+**Why fpdf2 and not reportlab**, since reportlab is the better layout engine and
+was tried first: a note here is as likely to be Burmese, Arabic or Chinese as
+English, and reportlab cannot draw two of those correctly at once. With its
+shaping off, Burmese and the Indic scripts lose their stacked clusters; with it
+on, they come back but Arabic reverses, because reordering a right-to-left run
+needs `rlbidi`, which reportlab publishes no build of. fpdf2 shapes through
+HarfBuzz and gets both right in one document, including an Arabic phrase inside
+an English sentence. Correct text beats prettier boxes.
+
+Two things a server cannot do on its own:
+
+- **Diagrams.** Drawing Mermaid needs a browser, so the caller renders each
+ fence and posts it as a PNG, keyed by the hash of its source. A fence with no
+ PNG falls back to its own source in a code box rather than vanishing.
+- **Remote images.** They stay out, as they did in the print export: opening a
+ note must not make the machine fetch anything (spec — local-first).
+"""
+
+from __future__ import annotations
+
+import hashlib
+import re
+from dataclasses import dataclass, field
+from io import BytesIO
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Iterable
+from urllib.parse import parse_qs, unquote, urlsplit
+
+from fpdf import FPDF
+from fpdf.enums import Align, XPos, YPos
+from markdown_it import MarkdownIt
+from markdown_it.token import Token
+from PIL import Image as PILImage
+from PIL import UnidentifiedImageError
+
+from . import pdffonts
+
+if TYPE_CHECKING:
+ from ..workspace import Case
+
+# -- the document's look -----------------------------------------------------
+#
+# Carried over from the print stylesheet this replaces, so an export made before
+# and after the change is recognisably the same document: serif body, sans
+# headings, and the app's amber as the one accent.
+
+ACCENT = (189, 122, 37)
+ACCENT_DARK = (109, 69, 21)
+INK = (32, 33, 36)
+MUTED = (119, 119, 119)
+RULE = (216, 209, 200)
+CODE_BG = (248, 246, 243)
+TABLE_HEAD_BG = (241, 236, 229)
+NOTE_BG = (250, 248, 245)
+
+MARGIN_TOP = 18.0
+MARGIN_SIDE = 16.0
+MARGIN_BOTTOM = 20.0
+#: A4 in millimetres, which is fpdf2's unit here.
+PAGE_WIDTH = 210.0
+PAGE_HEIGHT = 297.0
+FRAME_WIDTH = PAGE_WIDTH - 2 * MARGIN_SIDE
+
+BODY_SIZE = 10.0
+LEADING = 5.4
+GAP = 3.4
+
+#: A pixel is not a millimetre. Inline sizes are authored against the screen,
+#: where the notebook's own CSS reads them as CSS pixels at 96 dpi.
+PX_TO_MM = 25.4 / 96.0
+
+#: Bounds on what one note may cost. A note is a text file, but it can point at
+#: a hundred full-resolution captures, and a PDF holds every one of them.
+MAX_IMAGES = 200
+MAX_IMAGE_PIXELS = 50_000_000
+MAX_TABLE_COLUMNS = 12
+#: Room a list bullet takes before its item's text starts.
+BULLET_WIDTH = 5.5
+
+MERMAID_INFO = re.compile(r"^\s*mermaid\b")
+ENTITY_REF = re.compile(r"\[\[entity:([A-Za-z0-9_-]+)\|([^\]]+)\]\]")
+MEDIA_REF = re.compile(r"\[\[media:([A-Za-z0-9_-]+)\|([^\]]+)\]\](?:\{([^}\n]+)\})?")
+IMAGE_ATTRS = re.compile(r"!\[([^\]]*)\]\((\S+?)(?:\s+[\"']([^\"']*)[\"'])?\)\s*\{([^}\n]+)\}")
+ALIGNMENT_BLOCK = re.compile(r"^:::[ \t]*(left|center|right)[ \t]*\n(.*?)^:::[ \t]*$", re.S | re.M)
+ATTR_PARAM = "__azimut_attrs"
+ATTR_VALUES = re.compile(r"\b(width|align)\s*=\s*([\w.%+-]+)")
+WIDTH_PERCENT = re.compile(r"^(?:[1-9]\d?(?:\.\d+)?|100(?:\.0+)?)%$")
+WIDTH_PIXELS = re.compile(r"^(?:[2-9]\d|[1-9]\d{2}|1[0-5]\d{2}|1600)px$")
+
+ALIGNMENTS = {"left": Align.L, "center": Align.C, "right": Align.R}
+
+#: Heading sizes, h1 to h6, and the space above each.
+HEADINGS = {
+ "h1": (16.0, 7.0),
+ "h2": (13.5, 6.0),
+ "h3": (11.5, 5.0),
+ "h4": (10.5, 4.5),
+ "h5": (10.0, 4.0),
+ "h6": (9.5, 4.0),
+}
+
+
+class NotesPdfError(Exception):
+ """The note could not be turned into a document."""
+
+
+@dataclass
+class Rendered:
+ """One finished PDF, and what the analyst should know about it."""
+
+ pdf: bytes
+ #: One line per thing the page could not show — a remote image left out, a
+ #: script no font covers. Shown by the caller; never a reason to fail.
+ warnings: list[str] = field(default_factory=list)
+
+
+@dataclass
+class Run:
+ """A stretch of text drawn in one face, colour and link."""
+
+ text: str
+ bold: bool = False
+ italic: bool = False
+ mono: bool = False
+ color: tuple[int, int, int] = INK
+ link: str = ""
+
+
+def diagram_key(source: str) -> str:
+ """Identify a Mermaid fence by its source, not by its position.
+
+ The browser draws the diagrams and posts them back, so both sides have to
+ agree on which PNG belongs to which fence. A hash survives a fence being
+ moved while the export was in flight, and makes two identical diagrams in
+ one note share a single upload.
+ """
+ return hashlib.sha256(source.strip().encode("utf-8")).hexdigest()[:16]
+
+
+def mermaid_sources(text: str) -> list[str]:
+ """Every Mermaid fence in a note, in document order.
+
+ The caller draws these; it is here rather than in the frontend so one parser
+ decides what counts as a diagram.
+ """
+ return [
+ token.content
+ for token in _parser().parse(_case_references(text))
+ if token.type == "fence" and MERMAID_INFO.match(token.info or "")
+ ]
+
+
+def render(
+ case: "Case",
+ *,
+ title: str,
+ text: str,
+ diagrams: dict[str, bytes] | None = None,
+) -> Rendered:
+ """Lay one note out as a PDF."""
+ document = _Note(title=title)
+ pdffonts.install(document, f"{title}\n{text}")
+ builder = _Builder(document, case, diagrams or {})
+ try:
+ builder.build(title, text)
+ output = bytes(document.output())
+ except pdffonts.FontError:
+ raise
+ except Exception as exc: # fpdf2 raises bare errors for layout dead ends
+ raise NotesPdfError(f"the note could not be laid out: {exc}") from exc
+ return Rendered(pdf=output, warnings=builder.warnings)
+
+
+# -- source rewrites, mirroring lib/markdown.js ------------------------------
+
+
+def _attributed_url(href: str, attributes: str) -> str:
+ separator = "&" if "?" in href else "?"
+ return f"{href}{separator}{ATTR_PARAM}={_quote(attributes)}"
+
+
+def _quote(value: str) -> str:
+ """Percent-encode the way the preview's `encodeURIComponent` does."""
+ return "".join(
+ char if char.isalnum() or char in "-_.~" else f"%{ord(char):02X}" for char in value
+ )
+
+
+def _sized_image(match: re.Match[str]) -> str:
+ """`![alt](src){width=… align=…}` with its attributes folded into the URL."""
+ alt, href, title, attributes = match.groups()
+ caption = ' "%s"' % title if title else ""
+ return f"![{alt}]({_attributed_url(href, attributes)}{caption})"
+
+
+def _media_image(match: re.Match[str]) -> str:
+ """`[[media:id|label]]{…}` as the image the renderer resolves to a file."""
+ entity_id, label, attributes = match.groups()
+ query = f"?{ATTR_PARAM}={_quote(attributes)}" if attributes else ""
+ return f"![{label}](azimut://media/{entity_id}{query})"
+
+
+def _case_references(text: str) -> str:
+ """Turn Azimut's own syntax into links the Markdown parser understands."""
+ source = IMAGE_ATTRS.sub(_sized_image, str(text))
+ source = ENTITY_REF.sub(lambda m: f"[{m.group(2)}](azimut://entity/{m.group(1)})", source)
+ return MEDIA_REF.sub(_media_image, source)
+
+
+def _image_options(href: str) -> tuple[str, str, str]:
+ """Split an annotated image URL back into source, width and alignment."""
+ parts = urlsplit(href)
+ query = parse_qs(parts.query, keep_blank_values=True)
+ attributes = unquote(query.pop(ATTR_PARAM, [""])[0])
+ rebuilt = "&".join(f"{key}={value}" for key, values in query.items() for value in values)
+ source = parts._replace(query=rebuilt).geturl()
+ values = dict(ATTR_VALUES.findall(attributes))
+ width = values.get("width", "")
+ if not (WIDTH_PERCENT.match(width) or WIDTH_PIXELS.match(width)):
+ width = ""
+ align = values.get("align", "left")
+ return source, width, align if align in ALIGNMENTS else "left"
+
+
+def _parser() -> MarkdownIt:
+ """CommonMark plus the two GFM rules the preview enables (marked's `gfm`)."""
+ return MarkdownIt("commonmark").enable(["table", "strikethrough"])
+
+
+def _attr(token: Token, name: str) -> str:
+ """One token attribute as text; the parser types them loosely."""
+ value = token.attrGet(name)
+ return "" if value is None else str(value)
+
+
+# -- page furniture ----------------------------------------------------------
+
+
+class _Note(FPDF):
+ """A4 with a running footer: the note's name on the left, the page number
+ on the right, over a hairline."""
+
+ def __init__(self, *, title: str) -> None:
+ super().__init__(orientation="P", unit="mm", format="A4")
+ self.note_title = title
+ self.set_margins(MARGIN_SIDE, MARGIN_TOP, MARGIN_SIDE)
+ self.set_auto_page_break(True, margin=MARGIN_BOTTOM)
+ self.set_title(title)
+ self.set_creator("Azimut")
+ self.set_subject("Case notes")
+ # The analyst's own name is not ours to write into a file they share.
+ self.set_author("Azimut")
+
+ def footer(self) -> None:
+ self.set_y(-MARGIN_BOTTOM + 6)
+ self.set_draw_color(*RULE)
+ self.set_line_width(0.15)
+ self.line(MARGIN_SIDE, self.get_y(), PAGE_WIDTH - MARGIN_SIDE, self.get_y())
+ self.ln(1.5)
+ self.set_font(pdffonts.SANS, size=7.5)
+ self.set_text_color(*MUTED)
+ width = FRAME_WIDTH / 2
+ self.cell(width, 4, self.note_title, align=Align.L)
+ self.cell(width, 4, str(self.page_no()), align=Align.R)
+
+
+# -- Markdown to a page ------------------------------------------------------
+
+
+class _Builder:
+ """Walks the parsed note and draws it.
+
+ Kept as an object because the walk collects what the caller needs — the
+ warnings, and the running count of images a note is allowed to embed.
+ """
+
+ def __init__(self, pdf: _Note, case: "Case", diagrams: dict[str, bytes]) -> None:
+ self.pdf = pdf
+ self.case = case
+ self.diagrams = diagrams
+ self.warnings: list[str] = []
+ self.images = 0
+ #: How deep inside nested lists the walk currently is.
+ self._depth = 0
+ self._remote = 0
+ self._file_prefix = f"/files/{case.id}/"
+
+ # -- entry point --------------------------------------------------------
+
+ def build(self, title: str, text: str) -> None:
+ self.pdf.add_page()
+ self._title_block(title)
+ blocks = self._alignment_blocks(text)
+ drawn = False
+ for position, (alignment, tokens, index) in enumerate(blocks):
+ if position == 0:
+ index = _skip_repeated_title(tokens, title)
+ drawn = self._walk(tokens, index, alignment, stop=None)[0] or drawn
+ if not drawn:
+ self._aside("This note is empty.")
+ self._collect_warnings(f"{title}\n{text}")
+
+ def _title_block(self, title: str) -> None:
+ pdf = self.pdf
+ pdf.set_font(pdffonts.SANS, "B", 7.5)
+ pdf.set_text_color(*ACCENT_DARK)
+ pdf.cell(0, 4, "AZIMUT NOTES", new_x=XPos.LMARGIN, new_y=YPos.NEXT)
+ pdf.ln(1.5)
+ pdf.set_font(pdffonts.SANS, "B", 22)
+ pdf.set_text_color(24, 24, 24)
+ pdf.multi_cell(FRAME_WIDTH, 9, title, new_x=XPos.LMARGIN, new_y=YPos.NEXT)
+ pdf.ln(2)
+ pdf.set_draw_color(*ACCENT)
+ pdf.set_line_width(0.45)
+ pdf.line(MARGIN_SIDE, pdf.get_y(), PAGE_WIDTH - MARGIN_SIDE, pdf.get_y())
+ pdf.ln(6)
+
+ def _collect_warnings(self, text: str) -> None:
+ if self._remote:
+ self.warnings.append(
+ f"{self._remote} remote image{'s' if self._remote > 1 else ''} left out: "
+ "the export never fetches from the network."
+ )
+ missing = pdffonts.uncovered(self.pdf, text)
+ if missing:
+ scripts = sorted({pdffonts.script_of(char) for char in missing})
+ self.warnings.append(
+ f"No font on this machine covers {', '.join(scripts)}; "
+ "those characters were left out."
+ )
+
+ def _alignment_blocks(self, text: str) -> list[tuple[Align, list[Token], int]]:
+ """Parse the note, honouring the `::: center` blocks around parts of it.
+
+ Each block is parsed on its own so its alignment can be pushed into
+ everything it produced, which is how the preview reads it too.
+ """
+ blocks: list[tuple[Align, list[Token], int]] = []
+ position = 0
+ for match in ALIGNMENT_BLOCK.finditer(text):
+ blocks.append((Align.L, self._parse(text[position : match.start()]), 0))
+ blocks.append((ALIGNMENTS[match.group(1)], self._parse(match.group(2)), 0))
+ position = match.end()
+ blocks.append((Align.L, self._parse(text[position:]), 0))
+ return blocks
+
+ def _parse(self, source: str) -> list[Token]:
+ return _parser().parse(_case_references(source)) if source.strip() else []
+
+ # -- the token walk -----------------------------------------------------
+
+ def _walk(
+ self, tokens: list[Token], index: int, align: Align, stop: str | None
+ ) -> tuple[bool, int]:
+ """Draw one nesting level, stopping at `stop`. Returns whether it drew."""
+ drew = False
+ while index < len(tokens):
+ token = tokens[index]
+ if token.type == stop:
+ return drew, index + 1
+ handler = getattr(self, f"_on_{token.type}", None)
+ if handler is None:
+ index += 1
+ continue
+ index = handler(tokens, index, align)
+ drew = True
+ return drew, index
+
+ # -- blocks -------------------------------------------------------------
+
+ def _on_heading_open(self, tokens: list[Token], index: int, align: Align) -> int:
+ size, space = HEADINGS.get(tokens[index].tag, HEADINGS["h6"])
+ runs = self._inline(tokens[index + 1])
+ pdf = self.pdf
+ if pdf.get_y() > MARGIN_TOP + 2:
+ pdf.ln(space)
+ # A heading alone at the foot of a page belongs with what follows it, so
+ # what follows is measured rather than assumed: two lines of text is one
+ # thing to reserve, a full-width capture is another.
+ if pdf.will_page_break(size * 0.7 + self._next_height(tokens, index + 3)):
+ pdf.add_page()
+ self._runs(
+ runs,
+ align=align,
+ size=size,
+ leading=size * 0.46,
+ family=pdffonts.SANS,
+ bold=True,
+ color=MUTED if tokens[index].tag == "h6" else INK,
+ bottom=1.8,
+ )
+ return index + 3
+
+ def _next_height(self, tokens: list[Token], index: int) -> float:
+ """How tall the block after a heading is, for pictures; two lines else.
+
+ Only pictures are measured, because they are the blocks tall enough to
+ leave a heading behind on its own.
+ """
+ if index >= len(tokens):
+ return LEADING * 2
+ token = tokens[index]
+ picture: tuple[int, int] | None = None
+ width_attr = ""
+ if token.type == "fence" and MERMAID_INFO.match(token.info or ""):
+ png = self.diagrams.get(diagram_key(token.content))
+ picture = _measure(BytesIO(png)) if png else None
+ elif token.type == "paragraph_open" and index + 1 < len(tokens):
+ children = [
+ child
+ for child in (tokens[index + 1].children or [])
+ if child.type != "softbreak"
+ ]
+ if len(children) == 1 and children[0].type == "image":
+ resolved = self._peek_image(children[0])
+ if resolved is not None:
+ picture = resolved
+ _, width_attr, _ = _image_options(_attr(children[0], "src"))
+ if picture is None:
+ return LEADING * 2
+ return _fit(picture, width_attr, FRAME_WIDTH)[1]
+
+ def _peek_image(self, token: Token) -> tuple[int, int] | None:
+ """An image's pixel size without counting it against the note's budget."""
+ images, remote = self.images, self._remote
+ try:
+ resolved = self._resolve_image(token)
+ finally:
+ self.images, self._remote = images, remote
+ return None if isinstance(resolved, str) else resolved[1]
+
+ def _on_paragraph_open(self, tokens: list[Token], index: int, align: Align) -> int:
+ inline = tokens[index + 1]
+ if self._standalone_image(inline, align):
+ return index + 3
+ runs = self._inline(inline)
+ if runs:
+ self._runs(runs, align=align, bottom=1.2 if self._depth else GAP)
+ return index + 3
+
+ def _on_hr(self, tokens: list[Token], index: int, align: Align) -> int:
+ pdf = self.pdf
+ pdf.ln(1.5)
+ pdf.set_draw_color(*RULE)
+ pdf.set_line_width(0.2)
+ pdf.line(MARGIN_SIDE, pdf.get_y(), PAGE_WIDTH - MARGIN_SIDE, pdf.get_y())
+ pdf.ln(GAP + 1.5)
+ return index + 1
+
+ def _on_fence(self, tokens: list[Token], index: int, align: Align) -> int:
+ token = tokens[index]
+ if MERMAID_INFO.match(token.info or ""):
+ self._diagram(token.content)
+ else:
+ self._code_box(token.content)
+ return index + 1
+
+ def _on_code_block(self, tokens: list[Token], index: int, align: Align) -> int:
+ self._code_box(tokens[index].content)
+ return index + 1
+
+ def _on_blockquote_open(self, tokens: list[Token], index: int, align: Align) -> int:
+ pdf = self.pdf
+ top = pdf.get_y()
+ page = pdf.page
+ with self._indent(5.0):
+ _, index = self._walk(tokens, index + 1, align, stop="blockquote_close")
+ # Only bar the part on this page: a quote that split has a second half
+ # whose top is nowhere near where it started.
+ if pdf.page == page:
+ pdf.set_draw_color(*ACCENT)
+ pdf.set_line_width(0.7)
+ pdf.line(MARGIN_SIDE + 0.4, top, MARGIN_SIDE + 0.4, pdf.get_y() - GAP)
+ return index
+
+ def _on_bullet_list_open(self, tokens: list[Token], index: int, align: Align) -> int:
+ return self._list(tokens, index, align, ordered=False)
+
+ def _on_ordered_list_open(self, tokens: list[Token], index: int, align: Align) -> int:
+ return self._list(tokens, index, align, ordered=True)
+
+ def _list(self, tokens: list[Token], index: int, align: Align, *, ordered: bool) -> int:
+ """A list, drawn as one hanging-indent paragraph per item.
+
+ The bullet is handed to the item's first paragraph rather than drawn
+ here, so a wrapped item lines up under its own text instead of under the
+ bullet, and a nested list indents from where its parent left off.
+ """
+ closing = "ordered_list_close" if ordered else "bullet_list_close"
+ number = int(tokens[index].attrGet("start") or 1) if ordered else 1
+ index += 1
+ self._depth += 1
+ while index < len(tokens) and tokens[index].type != closing:
+ if tokens[index].type != "list_item_open":
+ index += 1
+ continue
+ pdf = self.pdf
+ pdf.set_font(pdffonts.SERIF, size=BODY_SIZE)
+ pdf.set_text_color(*ACCENT_DARK)
+ pdf.set_x(pdf.l_margin + (1.5 if self._depth == 1 else 0.0))
+ pdf.cell(BULLET_WIDTH, LEADING, f"{number}." if ordered else "\u2022")
+ with self._indent(BULLET_WIDTH + 1.5):
+ _, index = self._walk(tokens, index + 1, align, stop="list_item_close")
+ number += 1
+ self._depth -= 1
+ if not self._depth:
+ self.pdf.ln(GAP - 1.6)
+ return index + 1
+
+ def _on_table_open(self, tokens: list[Token], index: int, align: Align) -> int:
+ rows: list[list[str]] = []
+ header_rows = 0
+ in_head = False
+ index += 1
+ while index < len(tokens) and tokens[index].type != "table_close":
+ token = tokens[index]
+ if token.type == "thead_open":
+ in_head = True
+ elif token.type == "thead_close":
+ in_head = False
+ elif token.type == "tr_open":
+ cells: list[str] = []
+ index += 1
+ while index < len(tokens) and tokens[index].type != "tr_close":
+ if tokens[index].type in ("th_open", "td_open"):
+ cells.append(_plain(self._inline(tokens[index + 1])))
+ index += 3
+ continue
+ index += 1
+ rows.append(cells)
+ if in_head:
+ header_rows += 1
+ index += 1
+ if rows:
+ self._table(rows, header_rows)
+ return index + 1
+
+ def _on_html_block(self, tokens: list[Token], index: int, align: Align) -> int:
+ # The preview sanitizes raw HTML away; here it is shown as what it is,
+ # so a note holding a stray tag neither executes nor disappears.
+ text = tokens[index].content.strip()
+ if text:
+ self._aside(text)
+ return index + 1
+
+ # -- inline -------------------------------------------------------------
+
+ def _inline(self, token: Token) -> list[Run]:
+ """One inline token stream flattened into styled runs."""
+ if token.type != "inline":
+ return []
+ runs: list[Run] = []
+ bold = italic = 0
+ link = ""
+ entity = 0
+ for child in token.children or []:
+ kind = child.type
+ if kind == "strong_open":
+ bold += 1
+ elif kind == "strong_close":
+ bold = max(0, bold - 1)
+ elif kind == "em_open":
+ italic += 1
+ elif kind == "em_close":
+ italic = max(0, italic - 1)
+ elif kind == "link_open":
+ link, entity = self._link_style(child)
+ elif kind == "link_close":
+ link, entity = "", 0
+ elif kind == "image":
+ runs.append(self._inline_image(child))
+ elif kind in ("text", "html_inline", "code_inline", "softbreak", "hardbreak"):
+ text = {"softbreak": " ", "hardbreak": "\n"}.get(kind, child.content)
+ if not text:
+ continue
+ colour = INK
+ if entity == 1:
+ colour = ACCENT_DARK
+ elif entity == 2 or (link and not entity):
+ colour = MUTED if entity else ACCENT_DARK
+ runs.append(
+ Run(
+ text=text,
+ bold=bool(bold) or entity == 1,
+ italic=bool(italic) or entity == 2,
+ mono=kind == "code_inline",
+ color=colour,
+ link="" if entity else link,
+ )
+ )
+ return [run for run in runs if run.text]
+
+ def _link_style(self, token: Token) -> tuple[str, int]:
+ """How a link is drawn, which depends on where it points.
+
+ A PDF is read away from the app, so a reference to another entity cannot
+ link anywhere. It stays visible as a reference, and turns quiet and
+ italic once the entity it named has been deleted from the case.
+ """
+ href = _attr(token, "href")
+ entity = re.match(r"^azimut://entity/([A-Za-z0-9_-]+)$", href)
+ if entity:
+ return "", 1 if self.case.get_entity(entity.group(1)) is not None else 2
+ return href, 0
+
+ def _inline_image(self, token: Token) -> Run:
+ """An image inside a run of text: named, not drawn.
+
+ fpdf2 places a picture at a point on the page, not in the middle of a
+ wrapping line, and a note that inlines a capture means it to be seen —
+ so it is drawn as its own block instead (`_standalone_image`).
+ """
+ resolved = self._resolve_image(token)
+ label = resolved if isinstance(resolved, str) else (token.content or "Image")
+ return Run(text=f"[{label}]", italic=True, color=MUTED)
+
+ # -- drawing ------------------------------------------------------------
+
+ def _indent(self, amount: float) -> "_Indent":
+ return _Indent(self.pdf, amount)
+
+ def _runs(
+ self,
+ runs: Iterable[Run],
+ *,
+ align: Align = Align.L,
+ size: float = BODY_SIZE,
+ leading: float = LEADING,
+ family: str = pdffonts.SERIF,
+ bold: bool = False,
+ color: tuple[int, int, int] = INK,
+ bottom: float = GAP,
+ ) -> None:
+ """Draw a paragraph of styled runs, wrapping and breaking pages itself.
+
+ Run by run through `write()`, and deliberately not through fpdf2's text
+ region, which lays a paragraph out word by word from left to right. That
+ is correct for English and wrong for Arabic: a right-to-left run comes
+ back with its words in reverse. `write()` keeps each run whole, so a
+ shaped right-to-left phrase lands the way HarfBuzz ordered it.
+
+ The cost is the line junction — a run that starts where the previous one
+ ran out of room gets its first word split — so the break is made here,
+ before the word rather than inside it.
+ """
+ pdf = self.pdf
+ if align is not Align.L:
+ # An aligned paragraph needs the whole line before it can be placed,
+ # so it is drawn as one string and gives up its inline styling.
+ pdf.set_font(family, "B" if bold else "", size)
+ pdf.set_text_color(*color)
+ pdf.multi_cell(
+ pdf.epw, leading, _plain(runs), align=align, new_x=XPos.LMARGIN, new_y=YPos.NEXT
+ )
+ pdf.ln(bottom)
+ return
+ # `write` keeps a cell margin on each side before it breaks, so the edge
+ # it measures against is inside the one the page declares.
+ right = PAGE_WIDTH - pdf.r_margin - 2 * pdf.c_margin
+ for run in runs:
+ emphasis = ("B" if run.bold or bold else "") + ("I" if run.italic else "")
+ run_family = pdffonts.MONO if run.mono else family
+ if run.mono:
+ emphasis = "" # the mono face ships in one weight
+ pdf.set_font(run_family, emphasis, size * (0.92 if run.mono else 1.0))
+ pdf.set_text_color(*(run.color if run.color != INK else color))
+ text = run.text
+ body = text.lstrip(" ")
+ word = body.split(" ", 1)[0] if body else ""
+ if word and pdf.get_x() + pdf.get_string_width(text[: len(text) - len(body)] + word) > right:
+ pdf.ln(leading)
+ text = body
+ pdf.write(leading, text, link=run.link or "")
+ pdf.ln(leading + bottom)
+
+ def _aside(self, message: str) -> None:
+ """A quiet, boxed line: what the page could not show, said in place."""
+ pdf = self.pdf
+ pdf.set_font(pdffonts.SERIF, "I", 9)
+ pdf.set_text_color(*MUTED)
+ pdf.set_fill_color(*NOTE_BG)
+ pdf.set_draw_color(*RULE)
+ pdf.set_line_width(0.5)
+ top = pdf.get_y()
+ pdf.set_x(MARGIN_SIDE + 2.5)
+ pdf.multi_cell(
+ FRAME_WIDTH - 2.5, 5.2, message, fill=True, new_x=XPos.LMARGIN, new_y=YPos.NEXT
+ )
+ pdf.line(MARGIN_SIDE + 0.6, top, MARGIN_SIDE + 0.6, pdf.get_y())
+ pdf.ln(GAP)
+
+ def _code_box(self, code: str) -> None:
+ """Preformatted text in a tinted box, indentation and all."""
+ pdf = self.pdf
+ size = 8.5
+ leading = 4.3
+ pdf.set_font(pdffonts.MONO, size=size)
+ lines = [
+ part
+ for line in code.rstrip("\n").split("\n")
+ for part in _hard_wrap(line, pdf, FRAME_WIDTH - 8)
+ ]
+ pdf.set_text_color(*INK)
+ left = pdf.l_margin
+ width = pdf.epw
+ # The tint is painted line by line, but the outline is drawn once per
+ # page over the block: a border per line would rule the box like a ledger.
+ pdf.ln(1.6)
+ chunk_top = pdf.get_y() - 1.6
+ for line in lines:
+ if pdf.will_page_break(leading + 1.6):
+ self._close_code_box(left, width, chunk_top, pdf.get_y() + 1.6)
+ pdf.add_page()
+ chunk_top = pdf.get_y()
+ pdf.ln(1.6)
+ pdf.set_fill_color(*CODE_BG)
+ pdf.rect(left, pdf.get_y(), width, leading, style="F")
+ pdf.set_x(left + 3)
+ # `cell` rather than a text region: it keeps the leading spaces,
+ # which in code are the meaning rather than decoration.
+ pdf.cell(width - 6, leading, line, new_x=XPos.LMARGIN, new_y=YPos.NEXT)
+ self._close_code_box(left, width, chunk_top, pdf.get_y() + 1.6)
+ pdf.ln(1.6 + GAP)
+
+ def _close_code_box(self, left: float, width: float, top: float, bottom: float) -> None:
+ pdf = self.pdf
+ pdf.set_fill_color(*CODE_BG)
+ pdf.rect(left, bottom - 1.6, width, 1.6, style="F")
+ pdf.set_draw_color(*RULE)
+ pdf.set_line_width(0.2)
+ pdf.rect(left, top, width, bottom - top, style="D")
+
+ def _table(self, rows: list[list[str]], header_rows: int) -> None:
+ pdf = self.pdf
+ columns = min(max(len(row) for row in rows), MAX_TABLE_COLUMNS)
+ squared = [(row + [""] * columns)[:columns] for row in rows]
+ pdf.set_font(pdffonts.SERIF, size=9)
+ pdf.set_text_color(*INK)
+ pdf.set_draw_color(*RULE)
+ pdf.set_line_width(0.2)
+ from fpdf.fonts import FontFace
+
+ with pdf.table(
+ col_widths=_column_widths(squared, columns),
+ line_height=5.0,
+ text_align=Align.L,
+ padding=(1.6, 2.2),
+ headings_style=FontFace(
+ family=pdffonts.SANS, emphasis="B", size_pt=9, fill_color=TABLE_HEAD_BG
+ ),
+ first_row_as_headings=bool(header_rows),
+ repeat_headings=1,
+ ) as table:
+ for line in squared:
+ row = table.row()
+ for cell in line:
+ row.cell(cell)
+ pdf.ln(GAP)
+
+ def _standalone_image(self, inline: Token, align: Align) -> bool:
+ """A paragraph that is nothing but one image becomes a block image."""
+ children = [child for child in (inline.children or []) if child.type != "softbreak"]
+ if len(children) != 1 or children[0].type != "image":
+ return False
+ token = children[0]
+ resolved = self._resolve_image(token)
+ if isinstance(resolved, str):
+ self._aside(resolved)
+ return True
+ path, natural = resolved
+ _, width_attr, image_align = _image_options(_attr(token, "src"))
+ self._place(path, natural, width_attr, ALIGNMENTS[image_align], _attr(token, "title"))
+ return True
+
+ def _place(
+ self,
+ source: Path | BytesIO,
+ natural: tuple[int, int],
+ width_attr: str,
+ align: Align,
+ caption: str,
+ ) -> None:
+ pdf = self.pdf
+ width, height = _fit(natural, width_attr, FRAME_WIDTH)
+ if pdf.will_page_break(height + (5 if caption else 0)):
+ pdf.add_page()
+ pdf.image(source, w=width, h=height, x=align)
+ if caption:
+ pdf.ln(1)
+ pdf.set_font(pdffonts.SANS, size=8)
+ pdf.set_text_color(*MUTED)
+ pdf.multi_cell(
+ pdf.epw, 4, caption, align=align, new_x=XPos.LMARGIN, new_y=YPos.NEXT
+ )
+ pdf.ln(GAP)
+
+ def _diagram(self, source: str) -> None:
+ """The PNG the browser drew for this fence, or the fence's own source."""
+ png = self.diagrams.get(diagram_key(source))
+ natural = _measure(BytesIO(png)) if png else None
+ if png is None or natural is None:
+ self._aside("Diagram not drawn.")
+ self._code_box(source)
+ return
+ self._place(BytesIO(png), natural, "", Align.C, "")
+
+ def _resolve_image(self, token: Token) -> tuple[Path, tuple[int, int]] | str:
+ """The file behind an image, or the line to print instead of it."""
+ source, _, _ = _image_options(_attr(token, "src"))
+ parts = urlsplit(source)
+ if parts.scheme in ("http", "https"):
+ self._remote += 1
+ return "External image not included in PDF."
+ if parts.scheme == "azimut" and parts.netloc == "media":
+ entity = self.case.get_entity(unquote(parts.path.lstrip("/")))
+ attrs = (entity or {}).get("attrs") or {}
+ if not entity or not attrs.get("path"):
+ return "Media unavailable"
+ if attrs.get("kind") == "video":
+ return "Video not included in PDF."
+ relative = str(attrs["path"])
+ elif source.startswith(self._file_prefix):
+ relative = unquote(source[len(self._file_prefix) :])
+ else:
+ return "Image not included in PDF."
+ if self.images >= MAX_IMAGES:
+ return "Image not included in PDF: this note holds too many."
+ try:
+ path = self.case.resolve_inside(relative)
+ except Exception:
+ return "Media unavailable"
+ natural = _measure(path)
+ if natural is None:
+ return "Media unavailable"
+ self.images += 1
+ return path, natural
+
+
+class _Indent:
+ """Move the left margin in for as long as a block is being drawn."""
+
+ def __init__(self, pdf: FPDF, amount: float) -> None:
+ self.pdf = pdf
+ self.amount = amount
+
+ def __enter__(self) -> None:
+ self.pdf.set_left_margin(self.pdf.l_margin + self.amount)
+ self.pdf.set_x(self.pdf.l_margin)
+
+ def __exit__(self, *_: Any) -> None:
+ self.pdf.set_left_margin(self.pdf.l_margin - self.amount)
+ self.pdf.set_x(self.pdf.l_margin)
+
+
+def _skip_repeated_title(tokens: list[Token], title: str) -> int:
+ """Where to start reading, past a heading that only repeats the title.
+
+ Plenty of notes open by restating their own name as an `# H1`. On screen
+ that is the only title there is; here the page already carries it.
+ """
+ if len(tokens) < 3 or tokens[0].type != "heading_open" or tokens[0].tag != "h1":
+ return 0
+ heading = (tokens[1].content or "").strip().casefold()
+ return 3 if heading == title.strip().casefold() else 0
+
+
+def _plain(runs: Iterable[Run]) -> str:
+ return "".join(run.text for run in runs)
+
+
+def _hard_wrap(line: str, pdf: FPDF, width: float) -> list[str]:
+ """Break a code line too wide for the page.
+
+ Code is preformatted, so nothing else will break it, and a line that runs
+ past the frame is a line the reader loses.
+ """
+ if not line:
+ return [""]
+ if pdf.get_string_width(line) <= width:
+ return [line]
+ per_char = pdf.get_string_width("0") or 1
+ size = max(8, int(width / per_char))
+ return [line[start : start + size] for start in range(0, len(line), size)]
+
+
+def _measure(source: Path | BytesIO) -> tuple[int, int] | None:
+ try:
+ with PILImage.open(source) as image:
+ if image.width * image.height > MAX_IMAGE_PIXELS:
+ return None
+ return image.width, image.height
+ except (OSError, UnidentifiedImageError, PILImage.DecompressionBombError):
+ return None
+ finally:
+ if isinstance(source, BytesIO):
+ source.seek(0)
+
+
+def _fit(natural: tuple[int, int], width_attr: str, available: float) -> tuple[float, float]:
+ """Size an image the way the preview does, then keep it inside the page."""
+ pixels_wide, pixels_high = natural
+ ratio = pixels_high / pixels_wide if pixels_wide else 1.0
+ if width_attr.endswith("%"):
+ width = available * float(width_attr[:-1]) / 100
+ elif width_attr.endswith("px"):
+ width = float(width_attr[:-2]) * PX_TO_MM
+ else:
+ width = pixels_wide * PX_TO_MM
+ width = min(width, available)
+ height = width * ratio
+ # A tall image left at full width runs off the bottom of the page, and fpdf2
+ # will not split a picture. Scale it down instead of losing it.
+ room = PAGE_HEIGHT - MARGIN_TOP - MARGIN_BOTTOM - 12
+ if height > room:
+ width *= room / height
+ height = room
+ return width, height
+
+
+def _column_widths(rows: list[list[str]], columns: int) -> list[float]:
+ """Share the width out by how much text each column holds, with a floor.
+
+ An even split turns a table of one long column and three short ones into a
+ column of single words; weighting by content is what makes it readable.
+ """
+ weights = [
+ max(1.0, max(len(row[column]) for row in rows) ** 0.5) for column in range(columns)
+ ]
+ floor = 8.0
+ room = 100.0 - floor * columns
+ total = sum(weights)
+ return [floor + room * weight / total for weight in weights]
+
+
+__all__ = [
+ "NotesPdfError",
+ "Rendered",
+ "diagram_key",
+ "mermaid_sources",
+ "render",
+]
diff --git a/src/azimut/engine/pdffonts.py b/src/azimut/engine/pdffonts.py
new file mode 100644
index 0000000..e02f255
--- /dev/null
+++ b/src/azimut/engine/pdffonts.py
@@ -0,0 +1,209 @@
+"""Fonts for the notes PDF, and what happens when a script has none.
+
+A PDF embeds the faces it draws with, so the export cannot lean on whatever the
+machine happens to have installed: the same note has to come out the same from
+the three binaries. The faces ship in `assets/fonts/` for that — see the README
+there for the list and the licences — and only the glyphs a document actually
+uses are embedded, so a note with three Burmese words does not carry the Burmese
+font.
+
+Three faces are always loaded and the other thirty-odd are not. A note in French
+should not pay to parse a Korean font, so the script faces are added per
+document, decided from the note's own text by the `SCRIPTS` table below: a
+character's Unicode range names both the face that draws it and the script the
+warning calls it, without opening a file to find out.
+
+Whatever is still uncovered is named. fpdf2 draws nothing for a glyph it has no
+face for, so the warning is the only sign the analyst would get — and "no font on
+this machine covers Cherokee" reads as a limit, where a silently short line reads
+as lost work.
+
+Text shaping is on for the whole document. Without it Arabic comes out unjoined
+and Burmese mis-stacked — text that looks like text and is wrong, which is worse
+than text that is missing.
+
+The faces go in as fpdf2 *fallbacks* rather than being switched by hand, which
+is what keeps a right-to-left phrase whole: fpdf2 picks a face per character and
+still hands the run to HarfBuzz in one piece.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from fpdf import FPDF
+
+FONT_DIR = Path(__file__).resolve().parent.parent / "assets" / "fonts"
+
+#: Families the document asks for by name.
+SERIF = "azimut-serif"
+SANS = "azimut-sans"
+MONO = "azimut-mono"
+
+#: (family, style) → file. Sans has no italic and mono no bold on purpose: each
+#: face is another half megabyte in all three binaries, and the ones left out
+#: only ever serve emphasis inside a heading or a code span.
+CORE_FACES: dict[tuple[str, str], str] = {
+ (SERIF, ""): "NotoSerif-Regular.ttf",
+ (SERIF, "B"): "NotoSerif-Bold.ttf",
+ (SERIF, "I"): "NotoSerif-Italic.ttf",
+ (SERIF, "BI"): "NotoSerif-BoldItalic.ttf",
+ (SANS, ""): "NotoSans-Regular.ttf",
+ (SANS, "B"): "NotoSans-Bold.ttf",
+ (MONO, ""): "NotoSansMono-Regular.ttf",
+}
+
+
+@dataclass(frozen=True)
+class Script:
+ """A writing system, the face that draws it and where it lives in Unicode."""
+
+ #: How a warning names it, so a failure reads as a limit and not as a bug.
+ name: str
+ file: str
+ ranges: tuple[tuple[int, int], ...]
+
+ def holds(self, code: int) -> bool:
+ return any(start <= code <= end for start, end in self.ranges)
+
+
+#: Living scripts, in code-point order. Historical ones (Cuneiform, Linear B,
+#: Ogham) are left out: they are a megabyte each for text no case will hold.
+#: Latin, Greek and Cyrillic are absent because the body faces already have
+#: them — this table is only consulted for what they lack.
+#:
+#: CJK is Droid Sans Fallback plus Nanum Gothic rather than Noto Sans CJK: 6 MB
+#: between them against 19 MB for Noto's, for the same coverage of Chinese,
+#: Japanese and Korean. Bundled rather than borrowed from the system, so a note
+#: exported on Windows and the same note exported on Linux are the same document.
+SCRIPTS: tuple[Script, ...] = (
+ Script("Armenian", "NotoSansArmenian-Regular.ttf", ((0x0530, 0x058F),)),
+ Script("Hebrew", "NotoSansHebrew-Regular.ttf", ((0x0590, 0x05FF),)),
+ Script(
+ "Arabic",
+ "NotoSansArabic-Regular.ttf",
+ ((0x0600, 0x06FF), (0x0750, 0x077F), (0xFB50, 0xFDFF), (0xFE70, 0xFEFF)),
+ ),
+ Script("Syriac", "NotoSansSyriac-Regular.ttf", ((0x0700, 0x074F),)),
+ Script("Thaana", "NotoSansThaana-Regular.ttf", ((0x0780, 0x07BF),)),
+ Script("N'Ko", "NotoSansNKo-Regular.ttf", ((0x07C0, 0x07FF),)),
+ Script("Devanagari", "NotoSansDevanagari-Regular.ttf", ((0x0900, 0x097F),)),
+ Script("Bengali", "NotoSansBengali-Regular.ttf", ((0x0980, 0x09FF),)),
+ Script("Gurmukhi", "NotoSansGurmukhi-Regular.ttf", ((0x0A00, 0x0A7F),)),
+ Script("Gujarati", "NotoSansGujarati-Regular.ttf", ((0x0A80, 0x0AFF),)),
+ Script("Odia", "NotoSansOriya-Regular.ttf", ((0x0B00, 0x0B7F),)),
+ Script("Tamil", "NotoSansTamil-Regular.ttf", ((0x0B80, 0x0BFF),)),
+ Script("Telugu", "NotoSansTelugu-Regular.ttf", ((0x0C00, 0x0C7F),)),
+ Script("Kannada", "NotoSansKannada-Regular.ttf", ((0x0C80, 0x0CFF),)),
+ Script("Malayalam", "NotoSansMalayalam-Regular.ttf", ((0x0D00, 0x0D7F),)),
+ Script("Sinhala", "NotoSansSinhala-Regular.ttf", ((0x0D80, 0x0DFF),)),
+ Script("Thai", "NotoSansThai-Regular.ttf", ((0x0E00, 0x0E7F),)),
+ Script("Lao", "NotoSansLao-Regular.ttf", ((0x0E80, 0x0EFF),)),
+ Script("Burmese", "NotoSansMyanmar-Regular.ttf", ((0x1000, 0x109F), (0xA9E0, 0xA9FF))),
+ Script("Georgian", "NotoSansGeorgian-Regular.ttf", ((0x10A0, 0x10FF), (0x2D00, 0x2D2F))),
+ Script("Ethiopic", "NotoSansEthiopic-Regular.ttf", ((0x1200, 0x139F),)),
+ Script("Cherokee", "NotoSansCherokee-Regular.ttf", ((0x13A0, 0x13FF), (0xAB70, 0xABBF))),
+ Script(
+ "Canadian Aboriginal syllabics",
+ "NotoSansCanadianAboriginal-Regular.ttf",
+ ((0x1400, 0x167F),),
+ ),
+ Script("Khmer", "NotoSansKhmer-Regular.ttf", ((0x1780, 0x17FF), (0x19E0, 0x19FF))),
+ Script("Mongolian", "NotoSansMongolian-Regular.ttf", ((0x1800, 0x18AF),)),
+ Script("Balinese", "NotoSansBalinese-Regular.ttf", ((0x1B00, 0x1B7F),)),
+ Script("Coptic", "NotoSansCoptic-Regular.ttf", ((0x2C80, 0x2CFF),)),
+ Script("Tifinagh", "NotoSansTifinagh-Regular.ttf", ((0x2D30, 0x2D7F),)),
+ Script(
+ "Korean",
+ "NanumGothic-Regular.ttf",
+ ((0x1100, 0x11FF), (0x3130, 0x318F), (0xA960, 0xA97F), (0xAC00, 0xD7FF)),
+ ),
+ Script("Yi", "NotoSansYi-Regular.ttf", ((0xA000, 0xA4CF),)),
+ Script("Vai", "NotoSansVai-Regular.ttf", ((0xA500, 0xA62B),)),
+ Script("Javanese", "NotoSansJavanese-Regular.ttf", ((0xA980, 0xA9DF),)),
+ Script("Cham", "NotoSansCham-Regular.ttf", ((0xAA00, 0xAA5F),)),
+ Script(
+ "Chinese and Japanese",
+ "DroidSansFallbackFull.ttf",
+ (
+ (0x2E80, 0x2FFF),
+ (0x3000, 0x312F),
+ (0x3190, 0x31EF),
+ (0x3200, 0x9FFF),
+ (0xF900, 0xFAFF),
+ (0x20000, 0x2FA1F),
+ ),
+ ),
+ Script("Adlam", "NotoSansAdlam-Regular.ttf", ((0x1E900, 0x1E95F),)),
+)
+
+#: Arrows, ticks, box drawing and degree signs — the punctuation a note collects
+#: from pasted terminal output and spreadsheets, which the Noto text faces do not
+#: carry. Always added, because it is small and almost every note wants one.
+SYMBOL_FAMILY = "azimut-symbols"
+SYMBOL_FILE = "DejaVuSans.ttf"
+
+
+class FontError(Exception):
+ """A face the export cannot do without is missing or unreadable."""
+
+
+def _add(pdf: "FPDF", family: str, style: str, filename: str) -> None:
+ path = FONT_DIR / filename
+ try:
+ pdf.add_font(family, style, str(path))
+ except (OSError, RuntimeError, ValueError) as exc:
+ raise FontError(f"the bundled font {filename} could not be read: {exc}") from exc
+
+
+def scripts_in(text: str) -> list[Script]:
+ """The script faces this text needs, in the table's order.
+
+ Decided from the characters alone, so a note that is only Latin never opens
+ a font file it will not draw with.
+ """
+ codes = {ord(char) for char in set(text) if not char.isascii()}
+ return [script for script in SCRIPTS if any(script.holds(code) for code in codes)]
+
+
+def install(pdf: "FPDF", text: str) -> None:
+ """Load the faces this document needs and turn shaping on.
+
+ The script faces go in as fallbacks: fpdf2 then picks one per character, so
+ a Burmese word inside an English sentence keeps its own face and its own
+ shaping without the caller cutting the line into runs.
+ """
+ for (family, style), filename in CORE_FACES.items():
+ _add(pdf, family, style, filename)
+ _add(pdf, SYMBOL_FAMILY, "", SYMBOL_FILE)
+ fallbacks = [SYMBOL_FAMILY]
+ for script in scripts_in(text):
+ family = f"azimut-{Path(script.file).stem.lower()}"
+ _add(pdf, family, "", script.file)
+ fallbacks.append(family)
+ # Symbols last: a script face is the better answer whenever it has the glyph.
+ pdf.set_fallback_fonts([*fallbacks[1:], SYMBOL_FAMILY], exact_match=False)
+ pdf.set_text_shaping(True)
+
+
+def uncovered(pdf: "FPDF", text: str) -> set[str]:
+ """Characters no loaded face can draw, which the caller names in a warning."""
+ # A core font is one of the PDF base fourteen and has no cmap to read; only
+ # the TrueType faces this module adds are worth asking.
+ charmaps = [font.cmap for font in pdf.fonts.values() if hasattr(font, "cmap")]
+ missing = set()
+ for char in set(text):
+ if char.isascii() or char in "\n\r\t":
+ continue
+ if not any(ord(char) in charmap for charmap in charmaps):
+ missing.add(char)
+ return missing
+
+
+def script_of(char: str) -> str:
+ """What to call this character's script in a warning."""
+ code = ord(char)
+ return next((script.name for script in SCRIPTS if script.holds(code)), "some characters")
diff --git a/src/azimut/server.py b/src/azimut/server.py
index ad49e11..2849a0a 100644
--- a/src/azimut/server.py
+++ b/src/azimut/server.py
@@ -11,6 +11,7 @@ from typing import Any, AsyncIterator
from fastapi import FastAPI, Request
from fastapi.responses import FileResponse, JSONResponse, PlainTextResponse
from fastapi.staticfiles import StaticFiles
+from starlette.types import ASGIApp, Message, Receive, Scope, Send
from . import __version__, config
from .engine import workspacelock, workspacemove
@@ -34,6 +35,67 @@ SERVE_PORT: int | None = None
LOCAL_HOSTNAMES = frozenset({"127.0.0.1", "localhost", "::1", "[::1]"})
+class NotesPdfBodyLimit:
+ """Bound the one JSON route that can carry binary images before parsing."""
+
+ def __init__(self, app: ASGIApp) -> None:
+ self.app = app
+
+ @staticmethod
+ def _matches(scope: Scope) -> bool:
+ parts = str(scope.get("path", "")).split("/")
+ return scope.get("method") == "POST" and len(parts) == 6 and (
+ parts[1], parts[2], parts[4], parts[5]
+ ) == ("api", "cases", "notes", "pdf")
+
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
+ if scope["type"] != "http" or not self._matches(scope):
+ await self.app(scope, receive, send)
+ return
+
+ # Import lazily so the route owns the limit and tests can lower it
+ # without rebuilding the application.
+ from .api import notes
+
+ headers = dict(scope.get("headers", []))
+ raw_length = headers.get(b"content-length", b"")
+ try:
+ content_length = int(raw_length) if raw_length else None
+ except ValueError:
+ content_length = None
+ if content_length is not None and content_length > notes.MAX_PDF_BODY_BYTES:
+ await JSONResponse(
+ {"detail": "request body too large"}, status_code=413
+ )(scope, receive, send)
+ return
+
+ body = bytearray()
+ while True:
+ message = await receive()
+ if message["type"] != "http.request":
+ break
+ chunk = message.get("body", b"")
+ if len(body) + len(chunk) > notes.MAX_PDF_BODY_BYTES:
+ await JSONResponse(
+ {"detail": "request body too large"}, status_code=413
+ )(scope, receive, send)
+ return
+ body.extend(chunk)
+ if not message.get("more_body", False):
+ break
+
+ sent = False
+
+ async def replay() -> Message:
+ nonlocal sent
+ if sent:
+ return {"type": "http.disconnect"}
+ sent = True
+ return {"type": "http.request", "body": bytes(body), "more_body": False}
+
+ await self.app(scope, replay, send)
+
+
def _hostname(value: str) -> str:
"""The bare host of a Host or Origin header — no scheme, path or port."""
host = value.strip().lower()
@@ -169,16 +231,21 @@ def create_app() -> FastAPI:
title="Azimut", version=__version__, docs_url="/api/docs", lifespan=lifespan
)
- from .api import cases, drafts, events, files, ingest, inspect, media, proofs, satellite, settings, templates
+ from .api import (
+ cases, drafts, events, files, folders, ingest, inspect, media, notes, proofs,
+ satellite, settings, templates,
+ )
app.include_router(cases.router)
app.include_router(cases.workspace_router)
+ app.include_router(notes.router)
app.include_router(media.router)
app.include_router(inspect.router)
app.include_router(satellite.router)
app.include_router(proofs.router)
app.include_router(drafts.router)
app.include_router(files.router)
+ app.include_router(folders.router)
app.include_router(settings.router)
app.include_router(ingest.router)
app.include_router(events.router)
@@ -188,6 +255,8 @@ def create_app() -> FastAPI:
# Inside the local guard: a request that isn't allowed to reach the app at
# all should not learn whether the workspace is there.
install_availability_guard(app)
+ # Bound diagram-carrying JSON before FastAPI/Pydantic materialises it.
+ app.add_middleware(NotesPdfBodyLimit)
# last, so it wraps everything: refuse non-loopback Host / cross-origin web
install_local_guard(app)
diff --git a/src/azimut/sqlite_backend.py b/src/azimut/sqlite_backend.py
index d1d5932..3f427b6 100644
--- a/src/azimut/sqlite_backend.py
+++ b/src/azimut/sqlite_backend.py
@@ -866,6 +866,22 @@ class SqliteCase:
row = conn.execute("SELECT * FROM entities WHERE id = ?", (entity_id,)).fetchone()
return self._entity(row) if row is not None else None
+ def note_ids_by_titles(self, titles: set[str]) -> dict[str, list[str]]:
+ """Note ids grouped by case-folded title, for stable flat exports."""
+ wanted = {title.casefold() for title in titles}
+ grouped: dict[str, list[str]] = {title: [] for title in wanted}
+ if not wanted:
+ return grouped
+ with self._connect() as conn:
+ rows = conn.execute(
+ "SELECT id, label FROM entities WHERE type = 'note' ORDER BY id"
+ ).fetchall()
+ for row in rows:
+ key = str(row["label"]).casefold()
+ if key in grouped:
+ grouped[key].append(str(row["id"]))
+ return grouped
+
def find_entity(self, *, attr: str, value: Any) -> dict[str, Any] | None:
# Scan and match in Python so the store stays on core SQL (no JSON1
# dependency). A JSON1-indexed lookup is a later optimisation, gated on
diff --git a/src/azimut/workspace.py b/src/azimut/workspace.py
index b282132..9f95782 100644
--- a/src/azimut/workspace.py
+++ b/src/azimut/workspace.py
@@ -819,6 +819,9 @@ class Case:
def get_entity(self, entity_id: str) -> dict[str, Any] | None:
return self._graph().get_entity(entity_id)
+ def note_ids_by_titles(self, titles: set[str]) -> dict[str, list[str]]:
+ return self._graph().note_ids_by_titles(titles)
+
def entity_count(self) -> int:
"""Entity total for the case switcher — one indexed count."""
return self._graph().count_entities()
@@ -1133,6 +1136,8 @@ class Case:
attrs = entity.get("attrs") or {}
incoming = patch.get("attrs") or {}
if incoming.get("path"):
+ if "label" in patch:
+ patch["label"] = layout.slugify(str(patch["label"]), "Note")
return # the caller is stating where the file is, not renaming it
label = patch.get("label", entity.get("label"))
folder = incoming.get("folder", attrs.get("folder") or "")
diff --git a/tests/test_notes_pdf.py b/tests/test_notes_pdf.py
new file mode 100644
index 0000000..ee7dbe4
--- /dev/null
+++ b/tests/test_notes_pdf.py
@@ -0,0 +1,521 @@
+"""Notes rendered to PDF: the renderer, the fonts and the export route."""
+
+import base64
+import re
+import socket
+from io import BytesIO
+
+import pytest
+from PIL import Image
+from pypdf import PdfReader
+
+from azimut import layout
+from azimut.api import notes as notes_api
+from azimut.engine import notes_pdf, pdffonts
+from azimut.workspace import Case
+
+# -- helpers -----------------------------------------------------------------
+
+
+class FakeCase:
+ """Just enough case for the renderer: entities to resolve, files to read."""
+
+ def __init__(self, tmp_path, entities=None):
+ self.id = "demo"
+ self.path = tmp_path
+ self._entities = entities or {}
+
+ def get_entity(self, entity_id):
+ return self._entities.get(entity_id)
+
+ def resolve_inside(self, relative):
+ return self.path / relative
+
+
+def png(tmp_path, name, size=(400, 300), color="#4a5a6a"):
+ path = tmp_path / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ Image.new("RGB", size, color).save(path)
+ return path
+
+
+def png_bytes(size=(600, 200)):
+ buffer = BytesIO()
+ Image.new("RGB", size, "white").save(buffer, format="PNG")
+ return buffer.getvalue()
+
+
+def pdf_text(data: bytes) -> str:
+ """What a reader shows, across every page.
+
+ Read back rather than inspected: an embedded subset encodes text as glyph
+ codes, so the only honest check that a line reached the page is to decode it
+ the way a PDF reader would.
+ """
+ reader = PdfReader(BytesIO(data))
+ return "\n".join(page.extract_text() for page in reader.pages)
+
+
+def exports_of(case_id: str):
+ return layout.subdir(Case.open(case_id).path, "exports")
+
+
+# -- source rewrites ---------------------------------------------------------
+
+
+def test_case_syntax_becomes_markdown_the_parser_understands():
+ rewritten = notes_pdf._case_references(
+ "See [[entity:abc|The roof]] and [[media:m1|Frame]]{width=50% align=center}"
+ )
+ assert "[The roof](azimut://entity/abc)" in rewritten
+ assert "![Frame](azimut://media/m1?__azimut_attrs=width%3D50%25%20align%3Dcenter)" in rewritten
+ # The percent-encoding matches the preview's encodeURIComponent, so one
+ # spelling of an annotated URL is parsed by both sides.
+
+
+def test_image_attributes_survive_the_round_trip():
+ rewritten = notes_pdf._case_references('![alt](/files/demo/media/a.png "Cap"){width=70%}')
+ source, width, align = notes_pdf._image_options(
+ rewritten[rewritten.index("(") + 1 : rewritten.index(' "Cap")')]
+ )
+ assert (source, width, align) == ("/files/demo/media/a.png", "70%", "left")
+
+
+def test_only_bounded_widths_are_honoured():
+ assert notes_pdf._image_options("/a.png?__azimut_attrs=width%3D50%25")[1] == "50%"
+ assert notes_pdf._image_options("/a.png?__azimut_attrs=width%3D9000px")[1] == ""
+ assert notes_pdf._image_options("/a.png?__azimut_attrs=align%3Dsideways")[2] == "left"
+
+
+def test_mermaid_fences_are_found_in_document_order():
+ text = "```mermaid\ngraph TD; A-->B;\n```\n\ntext\n\n```mermaid\ngraph LR; C-->D;\n```\n"
+ sources = notes_pdf.mermaid_sources(text)
+ assert [s.strip() for s in sources] == ["graph TD; A-->B;", "graph LR; C-->D;"]
+ # The key follows the source, so a moved fence still finds its picture.
+ assert notes_pdf.diagram_key(sources[0]) == notes_pdf.diagram_key(" graph TD; A-->B; ")
+ assert notes_pdf.diagram_key(sources[0]) != notes_pdf.diagram_key(sources[1])
+
+
+# -- the document ------------------------------------------------------------
+
+
+def test_a_note_renders_to_a_real_pdf(tmp_path):
+ out = notes_pdf.render(FakeCase(tmp_path), title="Rooftop", text="# Heading\n\nBody text.\n")
+ assert out.pdf.startswith(b"%PDF-")
+ assert out.warnings == []
+ assert "Body text." in pdf_text(out.pdf)
+
+
+def test_the_title_is_not_printed_twice(tmp_path):
+ text = "# Rooftop\n\nBody.\n"
+ out = notes_pdf.render(FakeCase(tmp_path), title="Rooftop", text=text)
+ assert pdf_text(out.pdf).count("Rooftop") == 2 # the header, and the running footer
+ kept = notes_pdf.render(FakeCase(tmp_path), title="Rooftop", text="# Other heading\n\nB.\n")
+ assert "Other heading" in pdf_text(kept.pdf)
+
+
+def test_an_empty_note_still_produces_a_page(tmp_path):
+ out = notes_pdf.render(FakeCase(tmp_path), title="Blank", text=" \n")
+ assert out.pdf.startswith(b"%PDF-")
+ assert "This note is empty." in pdf_text(out.pdf)
+
+
+def test_a_deleted_reference_is_marked_rather_than_dropped(tmp_path):
+ case = FakeCase(tmp_path, {"live": {"id": "live", "label": "Roof", "attrs": {}}})
+ document = notes_pdf._Note(title="N")
+ pdffonts.install(document, "")
+ builder = notes_pdf._Builder(document, case, {})
+ tokens = notes_pdf._parser().parse(
+ notes_pdf._case_references("[[entity:live|Roof]] and [[entity:gone|Ghost]]\n")
+ )
+ runs = {run.text: run for run in builder._inline([t for t in tokens if t.type == "inline"][0])}
+ # A live reference reads as a reference; a deleted one goes quiet and italic
+ # rather than passing for ordinary text.
+ assert runs["Roof"].bold and not runs["Roof"].italic
+ assert runs["Ghost"].italic and runs["Ghost"].color == notes_pdf.MUTED
+ assert runs["Roof"].link == "" and runs["Ghost"].link == ""
+
+
+def test_local_images_are_embedded_and_remote_ones_are_not(tmp_path):
+ png(tmp_path, "media/roof.png")
+ case = FakeCase(tmp_path)
+ text = (
+ "![roof](/files/demo/media/roof.png)\n\n"
+ "![far](https://example.org/x.png)\n"
+ )
+ out = notes_pdf.render(case, title="Images", text=text)
+ assert "1 remote image left out" in " ".join(out.warnings)
+ assert "External image not included in PDF." in pdf_text(out.pdf)
+
+
+def test_rendering_never_reaches_the_network(tmp_path, monkeypatch):
+ def explode(*args, **kwargs):
+ raise AssertionError("the PDF export must not open a connection")
+
+ monkeypatch.setattr(socket, "socket", explode)
+ monkeypatch.setattr(socket, "create_connection", explode)
+ out = notes_pdf.render(
+ FakeCase(tmp_path),
+ title="Remote",
+ text="![far](https://example.org/x.png)\n\n[link](https://example.org)\n",
+ )
+ assert out.pdf.startswith(b"%PDF-")
+
+
+def test_a_media_reference_resolves_to_the_file_it_names(tmp_path):
+ png(tmp_path, "media/frame.png")
+ case = FakeCase(
+ tmp_path,
+ {
+ "m1": {
+ "id": "m1",
+ "label": "Frame",
+ "type": "capture",
+ "attrs": {"path": "media/frame.png", "kind": "image"},
+ },
+ "v1": {
+ "id": "v1",
+ "label": "Clip",
+ "type": "media",
+ "attrs": {"path": "media/clip.mp4", "kind": "video"},
+ },
+ "gone": {"id": "gone", "label": "Lost", "type": "media", "attrs": {}},
+ },
+ )
+ out = notes_pdf.render(
+ case,
+ title="Media",
+ text="[[media:m1|Frame]]\n\n[[media:v1|Clip]]\n\n[[media:gone|Lost]]\n",
+ )
+ text = pdf_text(out.pdf)
+ assert "Video not included in PDF." in text
+ assert "Media unavailable" in text
+
+
+def test_a_diagram_is_placed_when_the_browser_sends_it(tmp_path):
+ text = "```mermaid\ngraph TD; A-->B;\n```\n"
+ key = notes_pdf.diagram_key(notes_pdf.mermaid_sources(text)[0])
+ drawn = notes_pdf.render(
+ FakeCase(tmp_path), title="D", text=text, diagrams={key: png_bytes()}
+ )
+ assert "Diagram not drawn." not in pdf_text(drawn.pdf)
+ missing = notes_pdf.render(FakeCase(tmp_path), title="D", text=text)
+ # Without the picture the fence keeps its source rather than disappearing.
+ assert "Diagram not drawn." in pdf_text(missing.pdf)
+ assert "graph TD" in pdf_text(missing.pdf)
+
+
+def test_a_wide_code_line_is_broken_rather_than_overflowing(tmp_path):
+ long_line = "x = " + " + ".join(str(n) for n in range(200))
+ out = notes_pdf.render(FakeCase(tmp_path), title="Code", text=f"```\n{long_line}\n```\n")
+ assert out.pdf.startswith(b"%PDF-")
+
+
+def test_a_tall_image_is_scaled_to_stay_on_the_page(tmp_path):
+ png(tmp_path, "media/tall.png", size=(400, 6000))
+ out = notes_pdf.render(
+ FakeCase(tmp_path), title="Tall", text="![tall](/files/demo/media/tall.png)\n"
+ )
+ assert out.pdf.startswith(b"%PDF-")
+
+
+def test_tables_and_lists_survive_a_full_note(tmp_path):
+ text = (
+ "| Site | Distance |\n|---|---|\n| Roof | 120 m |\n\n"
+ "- [x] matched\n- [ ] pending\n\n"
+ "1. first\n2. second\n\n"
+ "> quoted line\n\n"
+ "::: center\ncentred\n:::\n"
+ )
+ out = notes_pdf.render(FakeCase(tmp_path), title="All", text=text)
+ rendered = pdf_text(out.pdf)
+ for expected in ("Site", "Distance", "matched", "first", "quoted line", "centred"):
+ assert expected in rendered
+
+
+# -- fonts -------------------------------------------------------------------
+
+
+def test_every_face_the_code_names_is_actually_shipped():
+ """The gate against a face named in the table but missing from the wheel.
+
+ A missing fallback degrades quietly at runtime — the script it covered turns
+ into replacement characters — so the mismatch has to fail here instead.
+ """
+ named = {
+ *pdffonts.CORE_FACES.values(),
+ *(script.file for script in pdffonts.SCRIPTS),
+ pdffonts.SYMBOL_FILE,
+ }
+ missing = sorted(name for name in named if not (pdffonts.FONT_DIR / name).is_file())
+ assert missing == []
+ # And nothing ships that no code path can reach.
+ shipped = {path.name for path in pdffonts.FONT_DIR.glob("*.ttf")}
+ assert sorted(shipped - named) == []
+
+
+def test_the_body_faces_carry_latin_greek_and_cyrillic_alone():
+ """Russian and Greek are body text, not a fallback: no extra file is opened."""
+ assert pdffonts.scripts_in("Русский текст, Ελληνικά, français, ĉ") == []
+
+
+def test_a_note_only_loads_the_faces_its_own_text_needs():
+ burmese = pdffonts.scripts_in("Sources: မြန်မာဘာသာစကား")
+ assert [script.name for script in burmese] == ["Burmese"]
+ mixed = pdffonts.scripts_in("中文, 한국어, العربية")
+ assert [script.name for script in mixed] == ["Arabic", "Korean", "Chinese and Japanese"]
+
+
+def test_scripts_are_named_the_way_a_reader_would_name_them():
+ for char, script in [("中", "Chinese and Japanese"), ("한", "Korean"), ("م", "Arabic"),
+ ("မ", "Burmese"), ("ก", "Thai"), ("ខ", "Khmer")]:
+ assert pdffonts.script_of(char) == script
+
+
+def test_every_script_the_table_names_renders_in_one_document(tmp_path):
+ samples = "Русский Ελληνικά 中文 日本語 한국어 العربية עברית မြန်မာ ไทย हिन्दी தமிழ் ქართული አማርኛ ខ្មែរ → ✓"
+ out = notes_pdf.render(FakeCase(tmp_path), title="Scripts", text=samples)
+ assert out.warnings == []
+ rendered = pdf_text(out.pdf)
+ for word in ("Русский", "中文", "한국어", "ไทย"):
+ assert word in rendered
+
+
+def test_a_script_nothing_covers_is_named_rather_than_drawn_blank(tmp_path):
+ char = "\U00013000" # Egyptian hieroglyph, deliberately not shipped
+ out = notes_pdf.render(FakeCase(tmp_path), title="Glyphs", text=f"Sign {char} here.\n")
+ assert out.pdf.startswith(b"%PDF-")
+ assert "No font on this machine covers" in " ".join(out.warnings)
+
+
+def test_a_missing_font_file_fails_by_name_rather_than_by_traceback(tmp_path, monkeypatch):
+ monkeypatch.setattr(pdffonts, "FONT_DIR", tmp_path / "nowhere")
+ with pytest.raises(pdffonts.FontError) as raised:
+ notes_pdf.render(FakeCase(tmp_path), title="Gone", text="Body.\n")
+ assert "NotoSerif-Regular.ttf" in str(raised.value)
+
+
+# -- the export route --------------------------------------------------------
+
+
+def make_case(client, name="Notes case"):
+ return client.post("/api/cases", json={"name": name}).json()["id"]
+
+
+def test_exporting_writes_one_pdf_per_note(client, tmp_path):
+ cid = make_case(client)
+ client.put(f"/api/cases/{cid}/notes", json={"text": "The case scratchpad.\n"})
+ first = client.post(
+ f"/api/cases/{cid}/notes", json={"title": "Rooftop", "content": "# Rooftop\n\nBody.\n"}
+ ).json()
+ second = client.post(
+ f"/api/cases/{cid}/notes", json={"title": "Mast", "content": "Second note.\n"}
+ ).json()
+
+ response = client.post(
+ f"/api/cases/{cid}/notes/pdf", json={"notes": ["case", first["id"], second["id"]]}
+ )
+ assert response.status_code == 200
+ body = response.json()
+ assert [row["file"] for row in body["written"]] == [
+ "Case notes.pdf",
+ "Rooftop.pdf",
+ "Mast.pdf",
+ ]
+ assert body["warnings"] == []
+
+ exports = exports_of(cid)
+ assert sorted(p.name for p in exports.glob("*.pdf")) == [
+ "Case notes.pdf",
+ "Mast.pdf",
+ "Rooftop.pdf",
+ ]
+ assert "Body." in pdf_text((exports / "Rooftop.pdf").read_bytes())
+
+
+def test_a_re_export_overwrites_rather_than_accumulating(client):
+ cid = make_case(client)
+ note = client.post(
+ f"/api/cases/{cid}/notes", json={"title": "Rooftop", "content": "First.\n"}
+ ).json()
+ client.post(f"/api/cases/{cid}/notes/pdf", json={"notes": [note["id"]]})
+ client.put(f"/api/cases/{cid}/notes/{note['id']}", json={"text": "Second, longer body.\n"})
+ again = client.post(f"/api/cases/{cid}/notes/pdf", json={"notes": [note["id"]]})
+
+ exports = exports_of(cid)
+ assert [p.name for p in exports.glob("*.pdf")] == ["Rooftop.pdf"]
+ assert again.json()["written"][0]["file"] == "Rooftop.pdf"
+ assert "Second, longer body." in pdf_text((exports / "Rooftop.pdf").read_bytes())
+
+
+def test_two_notes_with_one_title_keep_two_files(client):
+ cid = make_case(client)
+ first = client.post(
+ f"/api/cases/{cid}/notes", json={"title": "Summary", "folder": "video-1", "content": "A"}
+ ).json()
+ second = client.post(
+ f"/api/cases/{cid}/notes", json={"title": "Summary", "folder": "video-2", "content": "B"}
+ ).json()
+ written = client.post(
+ f"/api/cases/{cid}/notes/pdf", json={"notes": [first["id"], second["id"]]}
+ ).json()["written"]
+ by_note = {row["note"]: row["file"] for row in written}
+ assert len(set(by_note.values())) == 2
+ assert all(re.search(r" \[[0-9a-f]{16}\]\.pdf$", name) for name in by_note.values())
+
+ first_alone = client.post(
+ f"/api/cases/{cid}/notes/pdf", json={"notes": [first["id"]]}
+ ).json()["written"][0]
+ assert first_alone["file"] == by_note[first["id"]]
+
+
+def test_long_homonymous_titles_keep_their_stable_suffix(client):
+ cid = make_case(client)
+ first = client.post(
+ f"/api/cases/{cid}/notes", json={"title": "First", "folder": "a", "content": "A"}
+ ).json()
+ second = client.post(
+ f"/api/cases/{cid}/notes", json={"title": "Second", "folder": "b", "content": "B"}
+ ).json()
+ case = Case.open(cid)
+ legacy_title = "Very long title " * 30
+ case._graph().update_entity(first["id"], {"label": legacy_title})
+ case._graph().update_entity(second["id"], {"label": legacy_title})
+
+ written = client.post(
+ f"/api/cases/{cid}/notes/pdf", json={"notes": [first["id"], second["id"]]}
+ ).json()["written"]
+
+ names = [row["file"] for row in written]
+ assert len(set(names)) == 2
+ assert all(len(name) <= layout.MAX_MEDIA_NAME for name in names)
+ assert all(re.search(r" \[[0-9a-f]{16}\]\.pdf$", name) for name in names)
+
+
+def test_an_explicit_note_path_still_canonicalises_its_label(client):
+ cid = make_case(client)
+ note = client.post(
+ f"/api/cases/{cid}/notes", json={"title": "Short", "content": "A"}
+ ).json()
+ case = Case.open(cid)
+ path = note["attrs"]["path"]
+
+ updated = case.update_entity(
+ note["id"], {"label": "A" * 300, "attrs": {"path": path}}
+ )
+
+ assert updated["attrs"]["path"] == path
+ assert len(updated["label"]) == layout.MAX_SLUG
+
+
+def test_a_diagram_travels_with_the_request(client):
+ cid = make_case(client)
+ text = "```mermaid\ngraph TD; A-->B;\n```\n"
+ note = client.post(
+ f"/api/cases/{cid}/notes", json={"title": "Diagram", "content": text}
+ ).json()
+ key = notes_pdf.diagram_key(notes_pdf.mermaid_sources(text)[0])
+ payload = {
+ "notes": [note["id"]],
+ "diagrams": {key: base64.b64encode(png_bytes()).decode("ascii")},
+ }
+ assert client.post(f"/api/cases/{cid}/notes/pdf", json=payload).status_code == 200
+
+ assert "Diagram not drawn." not in pdf_text((exports_of(cid) / "Diagram.pdf").read_bytes())
+
+
+def test_the_browser_is_told_which_diagrams_to_draw(client):
+ cid = make_case(client)
+ shared = "```mermaid\ngraph TD; A-->B;\n```\n"
+ first = client.post(
+ f"/api/cases/{cid}/notes", json={"title": "One", "content": f"Intro\n\n{shared}"}
+ ).json()
+ second = client.post(
+ f"/api/cases/{cid}/notes",
+ json={"title": "Two", "content": f"{shared}\n```mermaid\ngraph LR; C-->D;\n```\n"},
+ ).json()
+
+ pending = client.post(
+ f"/api/cases/{cid}/notes/pdf/diagrams", json={"notes": [first["id"], second["id"]]}
+ ).json()["diagrams"]
+
+ # The diagram both notes hold is drawn once, not twice.
+ assert len(pending) == 2
+ assert [row["key"] for row in pending] == [
+ notes_pdf.diagram_key("graph TD; A-->B;"),
+ notes_pdf.diagram_key("graph LR; C-->D;"),
+ ]
+ assert "graph TD" in pending[0]["source"]
+
+
+def test_a_note_without_a_diagram_asks_for_nothing(client):
+ cid = make_case(client)
+ note = client.post(f"/api/cases/{cid}/notes", json={"title": "Plain", "content": "Text"}).json()
+ response = client.post(f"/api/cases/{cid}/notes/pdf/diagrams", json={"notes": [note["id"]]})
+ assert response.json() == {"diagrams": []}
+
+
+def test_the_export_refuses_what_it_cannot_trust(client):
+ cid = make_case(client)
+ note = client.post(f"/api/cases/{cid}/notes", json={"title": "N", "content": "x"}).json()
+ assert client.post(f"/api/cases/{cid}/notes/pdf", json={"notes": []}).status_code == 422
+ assert client.post(f"/api/cases/{cid}/notes/pdf", json={"notes": ["nope"]}).status_code == 404
+ bad_key = {"notes": [note["id"]], "diagrams": {"../etc": "AAAA"}}
+ assert client.post(f"/api/cases/{cid}/notes/pdf", json=bad_key).status_code == 422
+ bad_payload = {"notes": [note["id"]], "diagrams": {"abc123": "not base64!"}}
+ assert client.post(f"/api/cases/{cid}/notes/pdf", json=bad_payload).status_code == 422
+ huge = {"notes": [note["id"]], "diagrams": {f"k{n}": "AAAA" for n in range(200)}}
+ assert client.post(f"/api/cases/{cid}/notes/pdf", json=huge).status_code == 422
+
+
+def test_the_export_bounds_the_decoded_diagram_batch(client, monkeypatch):
+ cid = make_case(client)
+ note = client.post(f"/api/cases/{cid}/notes", json={"title": "N", "content": "x"}).json()
+ monkeypatch.setattr(notes_api, "MAX_DIAGRAM_TOTAL_BYTES", 5)
+ payload = {
+ "notes": [note["id"]],
+ "diagrams": {
+ "first": base64.b64encode(b"abc").decode("ascii"),
+ "second": base64.b64encode(b"def").decode("ascii"),
+ },
+ }
+
+ response = client.post(f"/api/cases/{cid}/notes/pdf", json=payload)
+
+ assert response.status_code == 422
+ assert response.json()["detail"] == "diagram batch too large"
+
+
+def test_pdf_request_body_is_bounded_with_and_without_content_length(
+ client, monkeypatch
+):
+ cid = make_case(client)
+ monkeypatch.setattr(notes_api, "MAX_PDF_BODY_BYTES", 20)
+ path = f"/api/cases/{cid}/notes/pdf"
+
+ sized = client.post(path, content=b"x" * 21, headers={"content-type": "application/json"})
+
+ def chunks():
+ yield b"x" * 11
+ yield b"y" * 11
+
+ streamed = client.post(path, content=chunks(), headers={"content-type": "application/json"})
+
+ assert sized.status_code == 413
+ assert streamed.status_code == 413
+
+
+def test_exporting_an_unknown_case_is_a_404(client):
+ assert client.post("/api/cases/ghost/notes/pdf", json={"notes": ["case"]}).status_code == 404
+
+
[email protected]("route", ["notes/pdf/reveal"])
+def test_revealing_the_export_folder_takes_no_path_from_the_browser(client, monkeypatch, route):
+ cid = make_case(client)
+ opened = []
+ from azimut.engine import reveal as reveal_engine
+
+ monkeypatch.setattr(reveal_engine, "reveal", lambda path, **_: opened.append(path))
+ response = client.post(f"/api/cases/{cid}/{route}")
+ assert response.status_code == 200
+ assert opened and opened[0].name == "exports"
diff --git a/uv.lock b/uv.lock
index 4a60ca3..12b40df 100644
--- a/uv.lock
+++ b/uv.lock
@@ -98,8 +98,10 @@ dependencies = [
{ name = "cryptography", version = "48.0.1", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'x86_64' and sys_platform == 'darwin'" },
{ name = "cryptography", version = "49.0.0", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine != 'x86_64' or sys_platform != 'darwin'" },
{ name = "fastapi" },
+ { name = "fpdf2" },
{ name = "gallery-dl" },
{ name = "httpx" },
+ { name = "markdown-it-py" },
{ name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" },
{ name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },
{ name = "opencv-python-headless" },
@@ -110,6 +112,7 @@ dependencies = [
{ name = "secretstorage", marker = "sys_platform == 'linux'" },
{ name = "tzdata" },
{ name = "tzfpy" },
+ { name = "uharfbuzz" },
{ name = "uvicorn", extra = ["standard"] },
{ name = "yt-dlp" },
]
@@ -119,6 +122,7 @@ dev = [
{ name = "httpx" },
{ name = "httpx2" },
{ name = "mypy" },
+ { name = "pypdf" },
{ name = "pytest" },
{ name = "pytest-asyncio" },
{ name = "ruff" },
@@ -136,15 +140,18 @@ requires-dist = [
{ name = "cryptography", marker = "platform_machine != 'x86_64' or sys_platform != 'darwin'", specifier = ">=45,<50" },
{ name = "cryptography", marker = "platform_machine == 'x86_64' and sys_platform == 'darwin'", specifier = ">=45,<49" },
{ name = "fastapi", specifier = ">=0.111,<1.0" },
+ { name = "fpdf2", specifier = ">=2.8,<3" },
{ name = "gallery-dl", specifier = ">=1.27" },
{ name = "httpx", specifier = ">=0.27,<1.0" },
{ name = "httpx", marker = "extra == 'dev'", specifier = ">=0.27,<1.0" },
{ name = "httpx2", marker = "extra == 'dev'", specifier = ">=2,<3" },
+ { name = "markdown-it-py", specifier = ">=4.0,<5" },
{ name = "mypy", marker = "extra == 'dev'", specifier = ">=2.3,<3" },
{ name = "numpy", specifier = ">=1.26,<3" },
{ name = "opencv-python-headless", specifier = ">=4.9,<5" },
{ name = "pillow", specifier = ">=10.3,<13" },
{ name = "pydantic", specifier = ">=2.7,<3" },
+ { name = "pypdf", marker = "extra == 'dev'", specifier = ">=6,<7" },
{ name = "pytest", marker = "extra == 'dev'", specifier = ">=8,<10" },
{ name = "pytest-asyncio", marker = "extra == 'dev'", specifier = ">=0.23,<2" },
{ name = "python-multipart", specifier = ">=0.0.9,<1.0" },
@@ -153,6 +160,7 @@ requires-dist = [
{ name = "secretstorage", marker = "sys_platform == 'linux'", specifier = ">=3.3,<4" },
{ name = "tzdata", specifier = ">=2024.1,<2027" },
{ name = "tzfpy", specifier = ">=1.3,<2" },
+ { name = "uharfbuzz", specifier = ">=0.50,<1" },
{ name = "uvicorn", extras = ["standard"], specifier = ">=0.30,<1.0" },
{ name = "yt-dlp", specifier = ">=2024.4.9" },
]
@@ -461,6 +469,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/aa/50/a9caea39ad19c431c1a3f8a31114df65b260cdfe67786b6c7e7c040c4c44/cryptography-49.0.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:be9fcb48a55f023493482827d4f459bd263cc20efde64f204b97c123201850c6", size = 3783731, upload-time = "2026-06-12T20:02:43.319Z" },
]
+[[package]]
+name = "defusedxml"
+version = "0.7.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/0f/d5/c66da9b79e5bdb124974bfe172b4daf3c984ebd9c2a06e2b8a4dc7331c72/defusedxml-0.7.1.tar.gz", hash = "sha256:1bb3032db185915b62d7c6209c5a8792be6a32ab2fedacc84e01b52c51aa3e69", size = 75520, upload-time = "2021-03-08T10:59:26.269Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/07/6c/aa3f2f849e01cb6a001cd8554a88d4c77c5c1a31c95bdf1cf9301e6d9ef4/defusedxml-0.7.1-py2.py3-none-any.whl", hash = "sha256:a352e7e428770286cc899e2542b6cdaedb2b4953ff269a210103ec58f6198a61", size = 25604, upload-time = "2021-03-08T10:59:24.45Z" },
+]
+
[[package]]
name = "fastapi"
version = "0.139.0"
@@ -477,6 +494,69 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/9e/7c/8e3c6ad324ea5cb36604fc3f968554887891c316d9dfde57761611d907ad/fastapi-0.139.0-py3-none-any.whl", hash = "sha256:cf15e1e9e667ddb0ad63811e60bd11390d1aac838ca4a7a23f421807b2308189", size = 130339, upload-time = "2026-07-01T16:35:32.19Z" },
]
+[[package]]
+name = "fonttools"
+version = "4.63.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/84/69/c97f2c18e0db87d2c7b15da1974dace76ae938f1cfa22e2727a648b7ed43/fonttools-4.63.0.tar.gz", hash = "sha256:caeb583deeb5168e694b65cda8b4ee62abedfa66cf88488734466f2366b9c4e0", size = 3597189, upload-time = "2026-05-14T12:04:30.958Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/75/2b/a7f1545bdf5da69c4bda0cea2a5781f0ad2a6623e0277267672db43c5fe6/fonttools-4.63.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:2b8ae05d9eacf6081414d759c0a352769ac28ce31280d6bb8e77b03f9e3c449f", size = 2881793, upload-time = "2026-05-14T12:02:56.645Z" },
+ { url = "https://files.pythonhosted.org/packages/49/50/965308c703f085f225db2886813b27e015b8b3438c350b22dd65b52c2a2c/fonttools-4.63.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:79cdc9f567aec74a72918fd060283911406750cbc9fd28c1316023deb6ce31a9", size = 2428130, upload-time = "2026-05-14T12:02:58.891Z" },
+ { url = "https://files.pythonhosted.org/packages/d8/38/6937fbd7f2dc3a6b48725851bc2c15ec949b9af14d9bbcb5fe83cdf9bdf9/fonttools-4.63.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2c14b4fd138c4bafcca294765c547914e1aa431ae1ca94ab99d8db08c958bd3b", size = 5111952, upload-time = "2026-05-14T12:03:01.263Z" },
+ { url = "https://files.pythonhosted.org/packages/0b/43/a81f20050a3115b57d62c8e781446949512eac36690dc384ccea65ff4cc1/fonttools-4.63.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d76ac49f929aecaf82d83250b8347e099d7aecba0f4726c1d9b6df3b8bb5fe18", size = 5082308, upload-time = "2026-05-14T12:03:03.211Z" },
+ { url = "https://files.pythonhosted.org/packages/67/00/cdd9d4944ca6ae280d01e69cc37bde3bf663630b837a6fc6d2cd65d80e0e/fonttools-4.63.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:dcf076a4474fe0d7367e5bbf5b052c7284fa1feca729c04176ce513521afd8a0", size = 5087932, upload-time = "2026-05-14T12:03:05.147Z" },
+ { url = "https://files.pythonhosted.org/packages/f5/f1/0aa0dbea778c75adbef223c42019fd47d22262b905974d62d829545d485f/fonttools-4.63.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:7dd683fef0663e9f0f45cf541d788d24caa3ec9db50796b588e1757d8b3bc007", size = 5213271, upload-time = "2026-05-14T12:03:07.238Z" },
+ { url = "https://files.pythonhosted.org/packages/a8/99/253e4056e1f0e67b9390125a154b73b5eb73ad521bece95c004858fdeec2/fonttools-4.63.0-cp311-cp311-win32.whl", hash = "sha256:afefc1ed0a59785a7fb06ea7e1678e849c193e1e387db783579bc7b3056fcfcb", size = 2304473, upload-time = "2026-05-14T12:03:09.271Z" },
+ { url = "https://files.pythonhosted.org/packages/08/60/defa5e69641db890a63be281f41345f4c33b157824eaf0b9fad3e08b0dcb/fonttools-4.63.0-cp311-cp311-win_amd64.whl", hash = "sha256:063e08bd17bd5a90127a14123de0d6a952dbc847695fd98b63c043d58057f90c", size = 2356389, upload-time = "2026-05-14T12:03:11.53Z" },
+ { url = "https://files.pythonhosted.org/packages/08/ef/b3c6b9b5be2f82416d73fe2ed2e96e2793cd80e7510bd6a17ca79cdd88ec/fonttools-4.63.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:37dd23e621e3b0aef1baa70a303b80aaf38449632cfc8fd2a55fb285bbccfc02", size = 2881131, upload-time = "2026-05-14T12:03:13.386Z" },
+ { url = "https://files.pythonhosted.org/packages/44/a0/c815bea63117fa63e4e1c01f8a1110d2112fa003f838e6467094ec2432ce/fonttools-4.63.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:a9faff9e0c1f76f9fd55899d2ce785832efebab37eb8ae13995853aef178bef0", size = 2426704, upload-time = "2026-05-14T12:03:15.801Z" },
+ { url = "https://files.pythonhosted.org/packages/44/04/0b91d8e916e92ad1fac9e4624760baf0fd5ff2ead614c2f68fb21373f03f/fonttools-4.63.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ef3048ef05dbb552b89817713d9cac912e00d0fde4a3105c00d29e52e10c89af", size = 5044298, upload-time = "2026-05-14T12:03:18.085Z" },
+ { url = "https://files.pythonhosted.org/packages/77/c7/2342da9830e3e9d4870305ca5d2091d2a83284f2953079b7bdd3b5e029d8/fonttools-4.63.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:58dc6bb86a78d782f00f9190ca02c119cf5bbe2807536e361e18d42019f877d8", size = 4999800, upload-time = "2026-05-14T12:03:20.161Z" },
+ { url = "https://files.pythonhosted.org/packages/e6/6d/67fe16c48d7ce050979b33f47e0d28a318f02da030602e944c34f7a16ef3/fonttools-4.63.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ee08ebfa58f6e1aeff5697ab9582105bb620008c1caafb681e4c557e7483027b", size = 4982666, upload-time = "2026-05-14T12:03:22.87Z" },
+ { url = "https://files.pythonhosted.org/packages/f2/00/3bbab338c07c71fa56269953845e92c951a61457bbbb0f1022551ea266d9/fonttools-4.63.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:27fdc65af8da6f88b9c6121c47a464cbe359fcfff7ff6fc2d37a1f395d755b78", size = 5133598, upload-time = "2026-05-14T12:03:25.168Z" },
+ { url = "https://files.pythonhosted.org/packages/62/f2/aa27c7f98db5b064883dadcc5283947e81e034de42e22a33675878d98b54/fonttools-4.63.0-cp312-cp312-win32.whl", hash = "sha256:af2fd1664d00a397d75f806985ddb36282091c2131a73a6485c23b4a34722263", size = 2292575, upload-time = "2026-05-14T12:03:27.496Z" },
+ { url = "https://files.pythonhosted.org/packages/87/36/cccb9bc2a6ab63d1b2980374f0dca72ce95ae267c9b4cfe77455bb70d0d4/fonttools-4.63.0-cp312-cp312-win_amd64.whl", hash = "sha256:59ac449f8cca9b4ffa08d2e7bbadad87ce710d69d1eda5c3c1ce579baa987272", size = 2343211, upload-time = "2026-05-14T12:03:30.057Z" },
+ { url = "https://files.pythonhosted.org/packages/0f/8d/d8fec3dcde2963f8c908fb315e5ff2cd0ac34f82394bbbf73a2aa5145ce3/fonttools-4.63.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:cd7e9857e5e63738b9d9fd707bc1f59c8b09e5177726d23664db393c59bb08bd", size = 2876062, upload-time = "2026-05-14T12:03:32.554Z" },
+ { url = "https://files.pythonhosted.org/packages/ef/71/d935dc54e4ff121bfdd11e08702db63a7e6f25af21d8a3d7b7212df53641/fonttools-4.63.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:c2a2a42198b696a6f48fad91709afb55176e66a5e566131219dba372fb7f8c59", size = 2424594, upload-time = "2026-05-14T12:03:34.86Z" },
+ { url = "https://files.pythonhosted.org/packages/8e/40/e76320afa1df918e146155ef239b1719ee266092e96f5423bfd075affba1/fonttools-4.63.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1e874792a8212b44583ea02189d9e693906b2f78b261f372f95d6c563210ac1d", size = 5024840, upload-time = "2026-05-14T12:03:36.745Z" },
+ { url = "https://files.pythonhosted.org/packages/ce/36/0b805d8c485f872f65a509cbe3b58a5d0d17bee855333b54a150c79d3061/fonttools-4.63.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:22135da48a348785c5e2d5d2d9d6bec5ed44adacbaeb9db12d9493bf6c6bfa68", size = 4975801, upload-time = "2026-05-14T12:03:38.833Z" },
+ { url = "https://files.pythonhosted.org/packages/c8/26/2cee03d0aa083ab022da5c07aff9ed3f689da1defb81ad6917c9627896da/fonttools-4.63.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:ccf41f2efdf56994d22d73bef4ced1052161958169428d06ba9724ea9e9a64be", size = 4965009, upload-time = "2026-05-14T12:03:41.494Z" },
+ { url = "https://files.pythonhosted.org/packages/7e/48/cc4b66d9058c0d0982c833fad10127c4b0e9324606aafa41382295ca4102/fonttools-4.63.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:9ced0bd02ac751dd6319b0da88aaef24414e3b0dbc32bb4f24944821a3741a27", size = 5105892, upload-time = "2026-05-14T12:03:43.525Z" },
+ { url = "https://files.pythonhosted.org/packages/d8/1f/a98a30a814b9ddef3a2e706025f90b9e0bc94890e6cb15254bc86547d11a/fonttools-4.63.0-cp313-cp313-win32.whl", hash = "sha256:85be818f5506e8a7753153def2c9550178f0ecae6a47b5e0e8dbb23f7cc90380", size = 2291313, upload-time = "2026-05-14T12:03:45.594Z" },
+ { url = "https://files.pythonhosted.org/packages/92/46/5177b01f3b4abfdd4409f31cca4ab279c9343a26efbe9ec78c97fc612e02/fonttools-4.63.0-cp313-cp313-win_amd64.whl", hash = "sha256:ba04cb5891d4c0c21b6da95eda8d7b090021508a294fff33464fc7d241e0856b", size = 2342299, upload-time = "2026-05-14T12:03:47.414Z" },
+ { url = "https://files.pythonhosted.org/packages/27/d2/23d25e3f247b328be58d04a4c9f894178a0d1eda7d42867cfb388adaf416/fonttools-4.63.0-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:fd1e3094f42d806d3d7c79162fc59e5910fcbe3a7360c385b8da969bc4493745", size = 2875338, upload-time = "2026-05-14T12:03:50.052Z" },
+ { url = "https://files.pythonhosted.org/packages/cd/58/7dfa0c761cb3b2964e2a84c4dc986c926a87de0cb9fb60d5b28ded3f2914/fonttools-4.63.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:6e528da43bc3791085f8cb6141b1d13e459226790240340fcbb4625649238b03", size = 2422661, upload-time = "2026-05-14T12:03:52.154Z" },
+ { url = "https://files.pythonhosted.org/packages/dd/87/64cfa18a7a1621d17b7f4502b2b0ed8a135a90c3db51ea590ee99043e76b/fonttools-4.63.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6b2248c5decb223562f7902ff6325077a073f608ee8e33e88ad88db734eb9f49", size = 5010526, upload-time = "2026-05-14T12:03:54.647Z" },
+ { url = "https://files.pythonhosted.org/packages/36/e1/a8933a72c45a87177fbde2696e0d0755c8c9062f8c077a961c6215fa27b1/fonttools-4.63.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:308f957cdeaf8abe4e5f2f124902ef405448af92c90f80e302a3b771c2e6116b", size = 4923946, upload-time = "2026-05-14T12:03:56.984Z" },
+ { url = "https://files.pythonhosted.org/packages/27/60/872e6e233b8c5e8b41413796ff18b7fe479661bd40147e071b450dfad7a1/fonttools-4.63.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:bf00f21eb5fb721dbaf73d1e9da6d02a1af7768f2ebcf9798be98beab8ba90f6", size = 4962489, upload-time = "2026-05-14T12:03:59.443Z" },
+ { url = "https://files.pythonhosted.org/packages/30/c4/83c24f2ec38b90cfda84bf4b1a1f49df80e84a1db4e7ac6e0d41bf23bc39/fonttools-4.63.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:c1aaa4b9c75798400ac043ce04d74e7830376c85095a5a6ed7cba2f17a266bf4", size = 5071870, upload-time = "2026-05-14T12:04:02.122Z" },
+ { url = "https://files.pythonhosted.org/packages/de/40/3ae22b60ff1d41ce0bd044b31238cdc72cef99f28b976f1e128ebd618c9b/fonttools-4.63.0-cp314-cp314-win32.whl", hash = "sha256:22693918177bd9ceabec4736d338045f357769416fc6b0b2508eefef75b08616", size = 2295026, upload-time = "2026-05-14T12:04:04.47Z" },
+ { url = "https://files.pythonhosted.org/packages/c3/d4/98078064ccc76b45cb0f6c002452011e93c4bd26f6850344f0951cc1fe89/fonttools-4.63.0-cp314-cp314-win_amd64.whl", hash = "sha256:7d782fac32985914c351556f68ac0855391572bcd87de50e05970d3cd4c96fc5", size = 2347454, upload-time = "2026-05-14T12:04:06.752Z" },
+ { url = "https://files.pythonhosted.org/packages/49/4e/652d1580c5f4e39f7d103b0c793e4773129ad633dce4addd0cf4dfebde02/fonttools-4.63.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:6db5140a60a5d731d21ec076745b40a310607731b0a565b50776393188649001", size = 2958152, upload-time = "2026-05-14T12:04:08.706Z" },
+ { url = "https://files.pythonhosted.org/packages/0e/55/ad864c9a9b219f552eb46b32cd7906c466e5a578ba0c3abfcc0fe7413eb6/fonttools-4.63.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7d76edbff9014094dbf03bd2d074709dfa6ec7aba13d838c937a2b33d2d6a86e", size = 2460809, upload-time = "2026-05-14T12:04:10.783Z" },
+ { url = "https://files.pythonhosted.org/packages/ea/2b/0aa8db70f18cf52e49b4ed5ecec68547f981160bf5ded3b5aed6faa0a6f9/fonttools-4.63.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0eac00b9118c3c2f87d272e45341871c5b3066baa3c86897fa634a7c3fb59096", size = 5148649, upload-time = "2026-05-14T12:04:12.747Z" },
+ { url = "https://files.pythonhosted.org/packages/7f/63/18e4369c25043096f1048e0c9915951adc4f842bd81c6b18155824d6fa99/fonttools-4.63.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:51394295f1a51de8b5f30bdb1e1b9a4231536c7064ef5c6e211eec19fa36036f", size = 4932147, upload-time = "2026-05-14T12:04:14.806Z" },
+ { url = "https://files.pythonhosted.org/packages/a1/3f/67f3eac2ffd8a98446c5022f8ed3864eac878a5ff7af8df4c8286dba16cc/fonttools-4.63.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:9e12f105d2b6342c559c298afb674006bb2893afc7102dcf8a1b55b0486b4e40", size = 5027237, upload-time = "2026-05-14T12:04:17.675Z" },
+ { url = "https://files.pythonhosted.org/packages/1a/ba/4e6214cb38a7b04779e97bb7636de9a5c7f20af7018d03dee0b64c08510a/fonttools-4.63.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:796f27556dbe094c4824f75ca85267e4df776c79036c8441469a4df37038c196", size = 5053933, upload-time = "2026-05-14T12:04:20.818Z" },
+ { url = "https://files.pythonhosted.org/packages/34/3b/214dcc19ee31d3d38fb5ad2755c11ef0514e5dc300bbaf41c0b69f393799/fonttools-4.63.0-cp314-cp314t-win32.whl", hash = "sha256:948428a275741f0b64b113c955425a953314f4b9ab9997f73a72c83e68e569c8", size = 2359326, upload-time = "2026-05-14T12:04:24.22Z" },
+ { url = "https://files.pythonhosted.org/packages/dd/1e/3ff1a9b523058c2eeb6a9d50f5574e2a738200d0d94107d5bc4105e8da3f/fonttools-4.63.0-cp314-cp314t-win_amd64.whl", hash = "sha256:6d4741eb179121cab9eea4cb2393d24492373a260d7945006358c08cfbf45419", size = 2425829, upload-time = "2026-05-14T12:04:26.829Z" },
+ { url = "https://files.pythonhosted.org/packages/2c/47/c99d5268f354002ce80f8d029cd9d7d872969da1de8b93d32de4dc56d6f4/fonttools-4.63.0-py3-none-any.whl", hash = "sha256:445af2eab030a16b9171ea8bdda7ebf7d96bda2df88ee182a464252f6e05e20d", size = 1164562, upload-time = "2026-05-14T12:04:29.092Z" },
+]
+
+[[package]]
+name = "fpdf2"
+version = "2.8.7"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "defusedxml" },
+ { name = "fonttools" },
+ { name = "pillow" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/27/f2/72feae0b2827ed38013e4307b14f95bf0b3d124adfef4d38a7d57533f7be/fpdf2-2.8.7.tar.gz", hash = "sha256:7060ccee5a9c7ab0a271fb765a36a23639f83ef8996c34e3d46af0a17ede57f9", size = 362351, upload-time = "2026-02-28T05:39:16.456Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/66/0a/cf50ecffa1e3747ed9380a3adfc829259f1f86b3fdbd9e505af789003141/fpdf2-2.8.7-py3-none-any.whl", hash = "sha256:d391fc508a3ce02fc43a577c830cda4fe6f37646f2d143d489839940932fbc19", size = 327056, upload-time = "2026-02-28T05:39:14.619Z" },
+]
+
[[package]]
name = "gallery-dl"
version = "1.32.6"
@@ -727,6 +807,27 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/c7/d1/a9f36f8ecdf0fb7c9b1e78c8d7af12b8c8754e74851ac7b94a8305540fc7/macholib-1.16.4-py2.py3-none-any.whl", hash = "sha256:da1a3fa8266e30f0ce7e97c6a54eefaae8edd1e5f86f3eb8b95457cae90265ea", size = 38117, upload-time = "2025-11-22T08:28:36.939Z" },
]
+[[package]]
+name = "markdown-it-py"
+version = "4.2.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "mdurl" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/06/ff/7841249c247aa650a76b9ee4bbaeae59370dc8bfd2f6c01f3630c35eb134/markdown_it_py-4.2.0.tar.gz", hash = "sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49", size = 82454, upload-time = "2026-05-07T12:08:28.36Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b3/81/4da04ced5a082363ecfa159c010d200ecbd959ae410c10c0264a38cac0f5/markdown_it_py-4.2.0-py3-none-any.whl", hash = "sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a", size = 91687, upload-time = "2026-05-07T12:08:27.182Z" },
+]
+
+[[package]]
+name = "mdurl"
+version = "0.1.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" },
+]
+
[[package]]
name = "mypy"
version = "2.3.0"
@@ -1243,6 +1344,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e7/31/f2d7343d8ed5f7c4678377886f6ce533e6eaaa131b252ce950114c2a7efa/pyinstaller_hooks_contrib-2026.6-py3-none-any.whl", hash = "sha256:fd13b8ac126b35361175edacd41a0d97080b75dd5f4b594ecefefff969509dd3", size = 457159, upload-time = "2026-06-08T22:37:14.722Z" },
]
+[[package]]
+name = "pypdf"
+version = "6.14.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/03/72/7dfd5ff1c9c37de97a731701f51af091325f123d9d4270361c9c69e4431f/pypdf-6.14.2.tar.gz", hash = "sha256:7873f502fe4385e79539b21d872392dc0c4e3714327c15881cbc7fbfd1f95b25", size = 6491182, upload-time = "2026-06-23T14:18:30.859Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/49/e6/136aa8993a2ae7214e0b0ef2edaa0d2e08d1d4e4982635b08a835ff31ec8/pypdf-6.14.2-py3-none-any.whl", hash = "sha256:3f07891af76dc002657e04993ab9b4de81de29f9013b9761d0b7968bff12e946", size = 349514, upload-time = "2026-06-23T14:18:28.867Z" },
+]
+
[[package]]
name = "pyproject-hooks"
version = "1.2.0"
@@ -1508,6 +1618,28 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/8f/b1/b4344e06435c001ce20078751cab7190d6fa180c2d62ae756f788c6620be/tzfpy-1.3.2-cp314-cp314t-win_amd64.whl", hash = "sha256:408af2823d88c4e709dc264d8025941829f04cffcb8613e7093bc567a2f21349", size = 4340205, upload-time = "2026-07-12T01:35:09.619Z" },
]
+[[package]]
+name = "uharfbuzz"
+version = "0.56.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/58/85/c7545959fdf6b9377b926c826f6d80bddf034ac361b09306d430a0f556a5/uharfbuzz-0.56.0.tar.gz", hash = "sha256:77f4ad1c9f32f44cc6f0c0c4f98fab54587719c96c810a043d01669f704d3e0c", size = 38643044, upload-time = "2026-07-31T16:43:53.61Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/5e/6d/e007fcdb9e11d5cac2c9d3ae8d260a57a3fd41eceffdf9c2624dc3909cb9/uharfbuzz-0.56.0-cp310-abi3-macosx_10_9_universal2.whl", hash = "sha256:86ceb18ce68cef062224ed9919f4925624f4d8e33869e27fe1d8edef1eba83e1", size = 3253438, upload-time = "2026-07-31T16:43:28.795Z" },
+ { url = "https://files.pythonhosted.org/packages/3e/50/a13e8930633fc376882d01566dd23322ab5b4db5b8daf75dba535057061e/uharfbuzz-0.56.0-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:beec7ae03ec5d0d130ca317795ff2ba24f75226a031c26a921e1706f8c59f36c", size = 1871496, upload-time = "2026-07-31T16:43:30.93Z" },
+ { url = "https://files.pythonhosted.org/packages/0c/8f/6541f3855ed2f592204363091276b0b19a00e6078d1a4ff9bbbdd5970021/uharfbuzz-0.56.0-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3b4bb4398270bbb8e1005a7a3d56acd5258c5b00484a06633cb30776da9cc3ab", size = 1949388, upload-time = "2026-07-31T16:43:32.845Z" },
+ { url = "https://files.pythonhosted.org/packages/cd/28/8a8f8d8d3513973d17cd83f057e2c85c6c813cb06b88245c9fe0242ecd1b/uharfbuzz-0.56.0-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:032382a82e3b9e2a460116aee2934bb713e4757efb68d7f11f55dbbb1ae57184", size = 2895856, upload-time = "2026-07-31T16:43:34.446Z" },
+ { url = "https://files.pythonhosted.org/packages/27/b1/a238405fcca1bab989b70adfe37182ba2d4394a8c2900037d3898e2a3dca/uharfbuzz-0.56.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:e3a80b0d94baf19be47708903246e2ff4bd1069e1f6bf9ed530bf1c9e3e476b4", size = 3006312, upload-time = "2026-07-31T16:43:36.41Z" },
+ { url = "https://files.pythonhosted.org/packages/14/fb/04a21974d722acaf389da834904f3635c23a23f377d07f81a58e1fb4eef4/uharfbuzz-0.56.0-cp310-abi3-pyemscripten_2025_0_wasm32.whl", hash = "sha256:f3631cb67335d94318d7b9514f8d5d860a68780d523a188317ecf7861754a395", size = 895029, upload-time = "2026-07-31T16:43:37.999Z" },
+ { url = "https://files.pythonhosted.org/packages/a2/db/4de0c571a8920e00f3c108d0bfda5d170111b670a7e1b5c49c24a7b46842/uharfbuzz-0.56.0-cp310-abi3-pyemscripten_2026_0_wasm32.whl", hash = "sha256:2ac2c4d59d0059265cad9d6c005dd330d36b2b4a2068626db7d09a1c18e5a05c", size = 893134, upload-time = "2026-07-31T16:43:39.436Z" },
+ { url = "https://files.pythonhosted.org/packages/c0/e6/c1d4bfa188eec34fec251a907d770840387272f2d2b90ec172a968df0904/uharfbuzz-0.56.0-cp310-abi3-win32.whl", hash = "sha256:45413c77ffdcec7ba94a3e6b8c3af384a28688dafee4bbf343afb85249af3f9a", size = 1086028, upload-time = "2026-07-31T16:43:41.046Z" },
+ { url = "https://files.pythonhosted.org/packages/96/84/6c63afa111bcaed79ac011fc112c4a8d8cb60904ff5999f2e435bb79db4a/uharfbuzz-0.56.0-cp310-abi3-win_amd64.whl", hash = "sha256:0e7c628f327ce862a8606de93766f001704a5201e97d598686730ef2c1605c03", size = 1410443, upload-time = "2026-07-31T16:43:42.593Z" },
+ { url = "https://files.pythonhosted.org/packages/18/19/e7f0a7c139a419fc890de5a5314dee8ae16f5a49cdc0632ad4bb07957a22/uharfbuzz-0.56.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:c4507b64a4c53fe9af89a47efbacffd707b20bb8afb3714f970390cd4319e476", size = 1571295, upload-time = "2026-07-31T16:43:44.221Z" },
+ { url = "https://files.pythonhosted.org/packages/ed/e1/2aeecb52d043a0da02807a6dddcdb0399caebfbd2fdd17f0655668dbbf82/uharfbuzz-0.56.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:4d5885586ccf247dff92033fdc15988c4c4931406e0faa445d0c6f0941061dc4", size = 1455110, upload-time = "2026-07-31T16:43:45.68Z" },
+ { url = "https://files.pythonhosted.org/packages/c7/fa/86c9601eb879fe858410a0bb74498c91186acd95f7d3fbec08717521ae72/uharfbuzz-0.56.0-pp311-pypy311_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0c707baaeabf3d90ae3fde6e12cdfa05a3f77b754aaa4b930a527aaf9d165d0e", size = 1697682, upload-time = "2026-07-31T16:43:47.296Z" },
+ { url = "https://files.pythonhosted.org/packages/2e/3a/2947144fe8f87e7056051cfe44877aa8f04b47d86e12168457598bb27c91/uharfbuzz-0.56.0-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:84aafa43bf29729d839ae7eabdbbfe86bea2b3a8594195231b79b94a7f5be07d", size = 1774181, upload-time = "2026-07-31T16:43:49.135Z" },
+ { url = "https://files.pythonhosted.org/packages/f7/50/b41d4b0ee13b6f152c912fb052ccea437bd0642c92824b779a20b87e1958/uharfbuzz-0.56.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:d8768c480c1474f856da26a2e7195ca24c25fdb08e71a8d2ea30b50a413df1a7", size = 1431797, upload-time = "2026-07-31T16:43:50.832Z" },
+]
+
[[package]]
name = "urllib3"
version = "2.7.0"