@blackbelt-technology/pi-dashboard-document-converter 0.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.pi/skills/document-converter/SKILL.md +79 -0
- package/README.md +106 -0
- package/engine/.dockerignore +4 -0
- package/engine/Dockerfile +75 -0
- package/engine/IMAGE_VERSION +1 -0
- package/engine/README.md +65 -0
- package/engine/VENDOR.md +40 -0
- package/engine/build-image.sh +29 -0
- package/engine/document_converter/LICENSE +21 -0
- package/engine/document_converter/__init__.py +365 -0
- package/engine/document_converter/__main__.py +5 -0
- package/engine/document_converter/asciidoc_converter.py +534 -0
- package/engine/document_converter/cli.py +751 -0
- package/engine/document_converter/code_renderer.py +356 -0
- package/engine/document_converter/converter.py +928 -0
- package/engine/document_converter/cover_page.py +448 -0
- package/engine/document_converter/diagram_resizer.py +311 -0
- package/engine/document_converter/diagram_sizing.py +357 -0
- package/engine/document_converter/docx_reader.py +627 -0
- package/engine/document_converter/field_updater.py +277 -0
- package/engine/document_converter/font_manager.py +850 -0
- package/engine/document_converter/frontmatter_parser.py +644 -0
- package/engine/document_converter/graphviz_renderer.py +354 -0
- package/engine/document_converter/image_extractor.py +281 -0
- package/engine/document_converter/image_style.py +237 -0
- package/engine/document_converter/logo_manager.py +1021 -0
- package/engine/document_converter/manifest_manager.py +288 -0
- package/engine/document_converter/mermaid_renderer.py +371 -0
- package/engine/document_converter/meta_mapper.py +398 -0
- package/engine/document_converter/pandoc_styles.py +222 -0
- package/engine/document_converter/pdf_converter.py +735 -0
- package/engine/document_converter/pdf_server.py +283 -0
- package/engine/document_converter/plantuml_renderer.py +460 -0
- package/engine/document_converter/plantuml_server.py +273 -0
- package/engine/document_converter/pyproject.toml +80 -0
- package/engine/document_converter/round_trip.py +312 -0
- package/engine/document_converter/spacing_applier.py +332 -0
- package/engine/document_converter/spacing_config.py +323 -0
- package/engine/document_converter/style_extractor.py +420 -0
- package/engine/document_converter/svg_embedder.py +294 -0
- package/engine/document_converter/system_variables.py +158 -0
- package/engine/document_converter/table_formatter.py +450 -0
- package/engine/document_converter/template_extractor.py +1334 -0
- package/engine/document_converter/template_manager.py +427 -0
- package/engine/document_converter/textbox_extractor.py +551 -0
- package/engine/document_converter/toc_generator.py +559 -0
- package/engine/document_converter/toc_style.py +290 -0
- package/engine/document_converter/tree_renderer.py +328 -0
- package/engine/document_converter/utils.py +134 -0
- package/engine/document_converter/variable_manager.py +394 -0
- package/engine/engine_cli.py +371 -0
- package/engine/frontmatter_filler/doc-meta.sample.yaml +106 -0
- package/engine/frontmatter_filler/fill.py +517 -0
- package/engine/markdown_table_profiler/profile.py +442 -0
- package/engine/nano-banana-styles.yaml +59 -0
- package/engine/tests/test_styled_diagrams.py +109 -0
- package/package.json +32 -0
- package/src/__tests__/engine.test.ts +72 -0
- package/src/__tests__/facade.test.ts +120 -0
- package/src/__tests__/integration.test.ts +101 -0
- package/src/__tests__/ocr.test.ts +34 -0
- package/src/__tests__/provenance.test.ts +89 -0
- package/src/__tests__/routing.test.ts +40 -0
- package/src/engine.ts +187 -0
- package/src/errors.ts +43 -0
- package/src/index.ts +179 -0
- package/src/ocr.ts +43 -0
- package/src/provenance.ts +79 -0
- package/src/routing.ts +49 -0
- package/src/schema.json +69 -0
- package/src/schema.ts +107 -0
- package/src/types.ts +90 -0
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"""Document manifest management for tracking conversion metadata and templates."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Dict, Optional, Any
|
|
4
|
+
from xml.etree import ElementTree as ET
|
|
5
|
+
from xml.dom import minidom
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def get_manifest_path(document_path: Path) -> Path:
|
|
10
|
+
"""Get the manifest file path for a document.
|
|
11
|
+
|
|
12
|
+
Args:
|
|
13
|
+
document_path: Path to the Markdown or DOCX file.
|
|
14
|
+
|
|
15
|
+
Returns:
|
|
16
|
+
Path to the corresponding _manifest.xml file.
|
|
17
|
+
"""
|
|
18
|
+
return document_path.parent / f"{document_path.stem}_manifest.xml"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def create_manifest(
|
|
22
|
+
document_name: str,
|
|
23
|
+
template_name: Optional[str] = None,
|
|
24
|
+
template_version: str = "1.0",
|
|
25
|
+
features: Optional[Dict[str, bool]] = None
|
|
26
|
+
) -> ET.Element:
|
|
27
|
+
"""Create a manifest XML element.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
document_name: Name of the source document.
|
|
31
|
+
template_name: Name of the template used (if any).
|
|
32
|
+
template_version: Version of the template.
|
|
33
|
+
features: Dictionary of feature flags.
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
XML Element containing the manifest.
|
|
37
|
+
"""
|
|
38
|
+
root = ET.Element('manifest', version='1.0')
|
|
39
|
+
|
|
40
|
+
# Document info
|
|
41
|
+
doc_elem = ET.SubElement(root, 'document')
|
|
42
|
+
doc_elem.text = document_name
|
|
43
|
+
|
|
44
|
+
# Timestamp
|
|
45
|
+
created = ET.SubElement(root, 'created')
|
|
46
|
+
created.text = datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
|
|
47
|
+
|
|
48
|
+
# Template info (if used)
|
|
49
|
+
if template_name:
|
|
50
|
+
template = ET.SubElement(root, 'template')
|
|
51
|
+
template.set('name', template_name)
|
|
52
|
+
template.set('version', template_version)
|
|
53
|
+
|
|
54
|
+
# Features
|
|
55
|
+
if features:
|
|
56
|
+
features_elem = ET.SubElement(root, 'features')
|
|
57
|
+
for feature, enabled in features.items():
|
|
58
|
+
feat = ET.SubElement(features_elem, feature.replace('_', '-'))
|
|
59
|
+
feat.set('enabled', str(enabled).lower())
|
|
60
|
+
|
|
61
|
+
return root
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def prettify_xml(elem: ET.Element) -> str:
|
|
65
|
+
"""Return a pretty-printed XML string.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
elem: XML Element to format.
|
|
69
|
+
|
|
70
|
+
Returns:
|
|
71
|
+
Formatted XML string.
|
|
72
|
+
"""
|
|
73
|
+
rough_string = ET.tostring(elem, encoding='unicode')
|
|
74
|
+
reparsed = minidom.parseString(rough_string)
|
|
75
|
+
return reparsed.toprettyxml(indent=" ")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def save_manifest(
|
|
79
|
+
manifest_path: Path,
|
|
80
|
+
document_name: str,
|
|
81
|
+
template_name: Optional[str] = None,
|
|
82
|
+
template_version: str = "1.0",
|
|
83
|
+
features: Optional[Dict[str, bool]] = None
|
|
84
|
+
) -> None:
|
|
85
|
+
"""Save a document manifest to file.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
manifest_path: Path to save the manifest.
|
|
89
|
+
document_name: Name of the source document.
|
|
90
|
+
template_name: Name of the template used (if any).
|
|
91
|
+
template_version: Version of the template.
|
|
92
|
+
features: Dictionary of feature flags.
|
|
93
|
+
"""
|
|
94
|
+
root = create_manifest(
|
|
95
|
+
document_name=document_name,
|
|
96
|
+
template_name=template_name,
|
|
97
|
+
template_version=template_version,
|
|
98
|
+
features=features
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
manifest_path.parent.mkdir(parents=True, exist_ok=True)
|
|
102
|
+
xml_string = prettify_xml(root)
|
|
103
|
+
manifest_path.write_text(xml_string, encoding='utf-8')
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def save_manifest_to_both_locations(
|
|
107
|
+
source_path: Path,
|
|
108
|
+
output_path: Path,
|
|
109
|
+
template_name: Optional[str] = None,
|
|
110
|
+
template_version: str = "1.0",
|
|
111
|
+
features: Optional[Dict[str, bool]] = None
|
|
112
|
+
) -> None:
|
|
113
|
+
"""Save manifest to both source and output locations.
|
|
114
|
+
|
|
115
|
+
Args:
|
|
116
|
+
source_path: Path to the source file (DOCX or MD).
|
|
117
|
+
output_path: Path to the output file.
|
|
118
|
+
template_name: Name of the template used (if any).
|
|
119
|
+
template_version: Version of the template.
|
|
120
|
+
features: Dictionary of feature flags.
|
|
121
|
+
"""
|
|
122
|
+
document_name = source_path.name
|
|
123
|
+
|
|
124
|
+
# Determine manifest paths
|
|
125
|
+
source_manifest = get_manifest_path(source_path)
|
|
126
|
+
output_manifest = get_manifest_path(output_path)
|
|
127
|
+
|
|
128
|
+
# Save to source location
|
|
129
|
+
save_manifest(
|
|
130
|
+
source_manifest,
|
|
131
|
+
document_name,
|
|
132
|
+
template_name,
|
|
133
|
+
template_version,
|
|
134
|
+
features
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
# Save to output location if different
|
|
138
|
+
if source_manifest != output_manifest:
|
|
139
|
+
save_manifest(
|
|
140
|
+
output_manifest,
|
|
141
|
+
document_name,
|
|
142
|
+
template_name,
|
|
143
|
+
template_version,
|
|
144
|
+
features
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def load_manifest(manifest_path: Path) -> Dict[str, Any]:
|
|
149
|
+
"""Load a document manifest from file.
|
|
150
|
+
|
|
151
|
+
Args:
|
|
152
|
+
manifest_path: Path to the manifest file.
|
|
153
|
+
|
|
154
|
+
Returns:
|
|
155
|
+
Dictionary containing manifest data.
|
|
156
|
+
"""
|
|
157
|
+
if not manifest_path.exists():
|
|
158
|
+
return {}
|
|
159
|
+
|
|
160
|
+
tree = ET.parse(manifest_path)
|
|
161
|
+
root = tree.getroot()
|
|
162
|
+
|
|
163
|
+
manifest = {
|
|
164
|
+
'version': root.get('version', '1.0'),
|
|
165
|
+
'document': '',
|
|
166
|
+
'created': '',
|
|
167
|
+
'template_name': None,
|
|
168
|
+
'template_version': None,
|
|
169
|
+
'features': {}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
# Parse document
|
|
173
|
+
doc_elem = root.find('document')
|
|
174
|
+
if doc_elem is not None and doc_elem.text:
|
|
175
|
+
manifest['document'] = doc_elem.text
|
|
176
|
+
|
|
177
|
+
# Parse created timestamp
|
|
178
|
+
created_elem = root.find('created')
|
|
179
|
+
if created_elem is not None and created_elem.text:
|
|
180
|
+
manifest['created'] = created_elem.text
|
|
181
|
+
|
|
182
|
+
# Parse template info
|
|
183
|
+
template_elem = root.find('template')
|
|
184
|
+
if template_elem is not None:
|
|
185
|
+
manifest['template_name'] = template_elem.get('name')
|
|
186
|
+
manifest['template_version'] = template_elem.get('version', '1.0')
|
|
187
|
+
|
|
188
|
+
# Parse features
|
|
189
|
+
features_elem = root.find('features')
|
|
190
|
+
if features_elem is not None:
|
|
191
|
+
for child in features_elem:
|
|
192
|
+
feature_name = child.tag.replace('-', '_')
|
|
193
|
+
manifest['features'][feature_name] = child.get('enabled', 'false').lower() == 'true'
|
|
194
|
+
|
|
195
|
+
return manifest
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def update_manifest_template(
|
|
199
|
+
manifest_path: Path,
|
|
200
|
+
template_name: str,
|
|
201
|
+
template_version: str = "1.0"
|
|
202
|
+
) -> None:
|
|
203
|
+
"""Update the template reference in an existing manifest.
|
|
204
|
+
|
|
205
|
+
Args:
|
|
206
|
+
manifest_path: Path to the manifest file.
|
|
207
|
+
template_name: New template name.
|
|
208
|
+
template_version: Template version.
|
|
209
|
+
"""
|
|
210
|
+
if not manifest_path.exists():
|
|
211
|
+
# Create new manifest with just template info
|
|
212
|
+
save_manifest(
|
|
213
|
+
manifest_path,
|
|
214
|
+
manifest_path.stem.replace('_manifest', ''),
|
|
215
|
+
template_name,
|
|
216
|
+
template_version
|
|
217
|
+
)
|
|
218
|
+
return
|
|
219
|
+
|
|
220
|
+
tree = ET.parse(manifest_path)
|
|
221
|
+
root = tree.getroot()
|
|
222
|
+
|
|
223
|
+
# Find or create template element
|
|
224
|
+
template_elem = root.find('template')
|
|
225
|
+
if template_elem is None:
|
|
226
|
+
template_elem = ET.SubElement(root, 'template')
|
|
227
|
+
|
|
228
|
+
template_elem.set('name', template_name)
|
|
229
|
+
template_elem.set('version', template_version)
|
|
230
|
+
|
|
231
|
+
# Save updated manifest
|
|
232
|
+
xml_string = prettify_xml(root)
|
|
233
|
+
manifest_path.write_text(xml_string, encoding='utf-8')
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def resolve_template_name(
|
|
237
|
+
md_path: Optional[Path] = None,
|
|
238
|
+
docx_path: Optional[Path] = None,
|
|
239
|
+
cli_template: Optional[str] = None
|
|
240
|
+
) -> Optional[str]:
|
|
241
|
+
"""Resolve template name using fallback chain.
|
|
242
|
+
|
|
243
|
+
Resolution order:
|
|
244
|
+
1. CLI argument (highest priority)
|
|
245
|
+
2. Markdown manifest
|
|
246
|
+
3. DOCX manifest (fallback)
|
|
247
|
+
|
|
248
|
+
Args:
|
|
249
|
+
md_path: Path to the Markdown file.
|
|
250
|
+
docx_path: Path to the DOCX file.
|
|
251
|
+
cli_template: Template name from CLI argument.
|
|
252
|
+
|
|
253
|
+
Returns:
|
|
254
|
+
Resolved template name, or None if not found.
|
|
255
|
+
"""
|
|
256
|
+
# 1. CLI argument takes priority
|
|
257
|
+
if cli_template:
|
|
258
|
+
return cli_template
|
|
259
|
+
|
|
260
|
+
# 2. Check Markdown manifest
|
|
261
|
+
if md_path:
|
|
262
|
+
md_manifest = get_manifest_path(md_path)
|
|
263
|
+
manifest = load_manifest(md_manifest)
|
|
264
|
+
if manifest.get('template_name'):
|
|
265
|
+
return manifest['template_name']
|
|
266
|
+
|
|
267
|
+
# 3. Fallback to DOCX manifest
|
|
268
|
+
if docx_path:
|
|
269
|
+
docx_manifest = get_manifest_path(docx_path)
|
|
270
|
+
manifest = load_manifest(docx_manifest)
|
|
271
|
+
if manifest.get('template_name'):
|
|
272
|
+
return manifest['template_name']
|
|
273
|
+
|
|
274
|
+
return None
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def get_template_from_manifest(document_path: Path) -> Optional[str]:
|
|
278
|
+
"""Get template name from a document's manifest.
|
|
279
|
+
|
|
280
|
+
Args:
|
|
281
|
+
document_path: Path to the document (MD or DOCX).
|
|
282
|
+
|
|
283
|
+
Returns:
|
|
284
|
+
Template name if found, None otherwise.
|
|
285
|
+
"""
|
|
286
|
+
manifest_path = get_manifest_path(document_path)
|
|
287
|
+
manifest = load_manifest(manifest_path)
|
|
288
|
+
return manifest.get('template_name')
|
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
"""Mermaid diagram extraction and rendering."""
|
|
2
|
+
import json
|
|
3
|
+
import re
|
|
4
|
+
import subprocess
|
|
5
|
+
import yaml
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from enum import Enum
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import List, Dict, Optional, Tuple, Any
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class DiagramFormat(Enum):
|
|
13
|
+
"""Output format for rendered diagrams."""
|
|
14
|
+
PNG = "png"
|
|
15
|
+
SVG = "svg"
|
|
16
|
+
AUTO = "auto"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class DiagramInfo:
|
|
21
|
+
"""Information about a rendered diagram.
|
|
22
|
+
|
|
23
|
+
Attributes:
|
|
24
|
+
path: Path to the rendered image file.
|
|
25
|
+
title: Optional title/caption from diagram metadata.
|
|
26
|
+
code: Original Mermaid code.
|
|
27
|
+
logical_width: Logical width in source units (CSS pixels for Mermaid).
|
|
28
|
+
logical_height: Logical height in source units.
|
|
29
|
+
units_per_inch: Conversion factor to inches (96 for CSS pixels, 72 for points).
|
|
30
|
+
"""
|
|
31
|
+
path: Path
|
|
32
|
+
title: Optional[str] = None
|
|
33
|
+
code: str = ""
|
|
34
|
+
logical_width: Optional[float] = None
|
|
35
|
+
logical_height: Optional[float] = None
|
|
36
|
+
units_per_inch: float = 96.0 # CSS pixels default
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def extract_svg_dimensions(svg_content: str) -> Tuple[Optional[float], Optional[float]]:
|
|
40
|
+
"""Extract logical dimensions from SVG viewBox or width/height attributes.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
svg_content: SVG file content as string.
|
|
44
|
+
|
|
45
|
+
Returns:
|
|
46
|
+
Tuple of (width, height) in logical units, or (None, None) if not found.
|
|
47
|
+
"""
|
|
48
|
+
# Try viewBox first (most reliable)
|
|
49
|
+
viewbox_match = re.search(r'viewBox="([^"]+)"', svg_content)
|
|
50
|
+
if viewbox_match:
|
|
51
|
+
parts = viewbox_match.group(1).split()
|
|
52
|
+
if len(parts) >= 4:
|
|
53
|
+
try:
|
|
54
|
+
return float(parts[2]), float(parts[3])
|
|
55
|
+
except ValueError:
|
|
56
|
+
pass
|
|
57
|
+
|
|
58
|
+
# Fall back to width/height attributes
|
|
59
|
+
width_match = re.search(r'<svg[^>]*\swidth="([0-9.]+)', svg_content)
|
|
60
|
+
height_match = re.search(r'<svg[^>]*\sheight="([0-9.]+)', svg_content)
|
|
61
|
+
|
|
62
|
+
width = float(width_match.group(1)) if width_match else None
|
|
63
|
+
height = float(height_match.group(1)) if height_match else None
|
|
64
|
+
|
|
65
|
+
return width, height
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def generate_mermaid_config(
|
|
69
|
+
font_size: int = 14,
|
|
70
|
+
font_family: str = "Source Sans Pro, sans-serif",
|
|
71
|
+
**kwargs: Any
|
|
72
|
+
) -> Dict[str, Any]:
|
|
73
|
+
"""Generate Mermaid configuration for consistent diagram rendering.
|
|
74
|
+
|
|
75
|
+
Creates a configuration dictionary that can be written to a JSON file
|
|
76
|
+
and passed to mmdc via the -c flag for consistent font sizing.
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
font_size: Base font size in pixels (default: 14).
|
|
80
|
+
font_family: CSS font family string (default: "Source Sans Pro, sans-serif").
|
|
81
|
+
**kwargs: Additional theme variables to override.
|
|
82
|
+
|
|
83
|
+
Returns:
|
|
84
|
+
Configuration dictionary for Mermaid CLI.
|
|
85
|
+
"""
|
|
86
|
+
config = {
|
|
87
|
+
"theme": "default",
|
|
88
|
+
"themeVariables": {
|
|
89
|
+
"fontSize": f"{font_size}px",
|
|
90
|
+
"fontFamily": font_family,
|
|
91
|
+
# Flowchart specific
|
|
92
|
+
"nodeTextColor": "#333",
|
|
93
|
+
# Sequence diagram specific
|
|
94
|
+
"actorFontSize": f"{font_size}px",
|
|
95
|
+
"messageFontSize": f"{font_size}px",
|
|
96
|
+
"noteFontSize": f"{font_size - 2}px",
|
|
97
|
+
# Class diagram specific
|
|
98
|
+
"classFontSize": f"{font_size}px",
|
|
99
|
+
# State diagram specific
|
|
100
|
+
"stateFontSize": f"{font_size}px",
|
|
101
|
+
# ER diagram specific
|
|
102
|
+
"entityFontSize": f"{font_size}px",
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
# Apply any additional overrides
|
|
107
|
+
if kwargs:
|
|
108
|
+
config["themeVariables"].update(kwargs)
|
|
109
|
+
|
|
110
|
+
return config
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def write_mermaid_config(config: Dict[str, Any], output_path: Path) -> Path:
|
|
114
|
+
"""Write Mermaid configuration to a JSON file.
|
|
115
|
+
|
|
116
|
+
Args:
|
|
117
|
+
config: Configuration dictionary.
|
|
118
|
+
output_path: Directory where config file should be written.
|
|
119
|
+
|
|
120
|
+
Returns:
|
|
121
|
+
Path to the created config file.
|
|
122
|
+
"""
|
|
123
|
+
config_path = output_path / "mermaid-config.json"
|
|
124
|
+
config_path.write_text(json.dumps(config, indent=2))
|
|
125
|
+
return config_path
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def resolve_diagram_format(output_suffix: str, format: DiagramFormat) -> str:
|
|
129
|
+
"""Resolve the actual diagram format based on output type and requested format.
|
|
130
|
+
|
|
131
|
+
Args:
|
|
132
|
+
output_suffix: The output file suffix (e.g., '.docx', '.md', '.html')
|
|
133
|
+
format: The requested diagram format.
|
|
134
|
+
|
|
135
|
+
Returns:
|
|
136
|
+
The resolved format string ('png' or 'svg').
|
|
137
|
+
"""
|
|
138
|
+
if format == DiagramFormat.AUTO:
|
|
139
|
+
# Use SVG for web/text formats, PNG for DOCX (compatibility)
|
|
140
|
+
if output_suffix.lower() in ('.docx', '.pdf'):
|
|
141
|
+
return 'png'
|
|
142
|
+
else:
|
|
143
|
+
return 'svg'
|
|
144
|
+
return format.value
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def extract_mermaid_blocks(markdown_content: str) -> List[str]:
|
|
148
|
+
"""Extract Mermaid code blocks from markdown content.
|
|
149
|
+
|
|
150
|
+
Args:
|
|
151
|
+
markdown_content: Markdown text containing Mermaid diagrams.
|
|
152
|
+
|
|
153
|
+
Returns:
|
|
154
|
+
List of Mermaid diagram code strings.
|
|
155
|
+
"""
|
|
156
|
+
pattern = r'```mermaid\n(.*?)```'
|
|
157
|
+
blocks = re.findall(pattern, markdown_content, re.DOTALL)
|
|
158
|
+
return [block.strip() for block in blocks]
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def extract_diagram_title(mermaid_code: str) -> Tuple[Optional[str], str]:
|
|
162
|
+
"""Extract title from Mermaid diagram's YAML frontmatter.
|
|
163
|
+
|
|
164
|
+
Mermaid supports YAML frontmatter at the beginning of the diagram:
|
|
165
|
+
```
|
|
166
|
+
---
|
|
167
|
+
title: "My Diagram Title"
|
|
168
|
+
---
|
|
169
|
+
flowchart LR
|
|
170
|
+
A --> B
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
Args:
|
|
174
|
+
mermaid_code: The Mermaid diagram code.
|
|
175
|
+
|
|
176
|
+
Returns:
|
|
177
|
+
Tuple of (title, code_without_frontmatter).
|
|
178
|
+
If no frontmatter, returns (None, original_code).
|
|
179
|
+
"""
|
|
180
|
+
mermaid_code = mermaid_code.strip()
|
|
181
|
+
|
|
182
|
+
# Check for YAML frontmatter (starts with ---)
|
|
183
|
+
if not mermaid_code.startswith('---'):
|
|
184
|
+
return (None, mermaid_code)
|
|
185
|
+
|
|
186
|
+
# Find the closing ---
|
|
187
|
+
lines = mermaid_code.split('\n')
|
|
188
|
+
frontmatter_end = -1
|
|
189
|
+
|
|
190
|
+
for i, line in enumerate(lines[1:], start=1):
|
|
191
|
+
if line.strip() == '---':
|
|
192
|
+
frontmatter_end = i
|
|
193
|
+
break
|
|
194
|
+
|
|
195
|
+
if frontmatter_end == -1:
|
|
196
|
+
return (None, mermaid_code)
|
|
197
|
+
|
|
198
|
+
# Extract frontmatter YAML
|
|
199
|
+
frontmatter_lines = lines[1:frontmatter_end]
|
|
200
|
+
frontmatter_str = '\n'.join(frontmatter_lines)
|
|
201
|
+
|
|
202
|
+
# Parse YAML
|
|
203
|
+
try:
|
|
204
|
+
frontmatter = yaml.safe_load(frontmatter_str)
|
|
205
|
+
if frontmatter and isinstance(frontmatter, dict):
|
|
206
|
+
title = frontmatter.get('title')
|
|
207
|
+
# Return code without frontmatter for rendering
|
|
208
|
+
code_without_fm = '\n'.join(lines[frontmatter_end + 1:]).strip()
|
|
209
|
+
return (title, code_without_fm)
|
|
210
|
+
except yaml.YAMLError:
|
|
211
|
+
pass
|
|
212
|
+
|
|
213
|
+
return (None, mermaid_code)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def render_diagram(
|
|
217
|
+
mermaid_code: str,
|
|
218
|
+
output_path: Path,
|
|
219
|
+
width: int = 1200,
|
|
220
|
+
scale: int = 2,
|
|
221
|
+
format: str = "png",
|
|
222
|
+
extract_dimensions: bool = False,
|
|
223
|
+
config_path: Optional[Path] = None
|
|
224
|
+
) -> Tuple[Path, Optional[float], Optional[float]]:
|
|
225
|
+
"""Render a single Mermaid diagram to image.
|
|
226
|
+
|
|
227
|
+
Args:
|
|
228
|
+
mermaid_code: Mermaid diagram code.
|
|
229
|
+
output_path: Path where image should be saved (extension will be adjusted).
|
|
230
|
+
width: Maximum width in pixels (default: 1200 for page fitting).
|
|
231
|
+
scale: Scale factor for higher resolution (default: 2 for better quality).
|
|
232
|
+
format: Output format - 'png' or 'svg' (default: 'png').
|
|
233
|
+
extract_dimensions: Whether to extract logical dimensions from SVG.
|
|
234
|
+
config_path: Optional path to Mermaid config JSON file for consistent styling.
|
|
235
|
+
|
|
236
|
+
Returns:
|
|
237
|
+
Tuple of (path to generated image, logical_width, logical_height).
|
|
238
|
+
Dimensions are None if extract_dimensions is False or extraction fails.
|
|
239
|
+
|
|
240
|
+
Raises:
|
|
241
|
+
RuntimeError: If rendering fails.
|
|
242
|
+
"""
|
|
243
|
+
# Adjust output path extension based on format
|
|
244
|
+
if format == "svg":
|
|
245
|
+
output_path = output_path.with_suffix('.svg')
|
|
246
|
+
else:
|
|
247
|
+
output_path = output_path.with_suffix('.png')
|
|
248
|
+
|
|
249
|
+
# Create temporary .mmd file
|
|
250
|
+
temp_mmd = output_path.with_suffix('.mmd')
|
|
251
|
+
temp_mmd.write_text(mermaid_code)
|
|
252
|
+
|
|
253
|
+
logical_width, logical_height = None, None
|
|
254
|
+
temp_svg_path = None
|
|
255
|
+
|
|
256
|
+
try:
|
|
257
|
+
# If we need dimensions and output is PNG, first render SVG to extract dimensions
|
|
258
|
+
if extract_dimensions and format == "png":
|
|
259
|
+
# Use _temp.svg suffix (mmdc requires .svg extension)
|
|
260
|
+
temp_svg_path = output_path.with_name(output_path.stem + '_temp.svg')
|
|
261
|
+
svg_cmd = [
|
|
262
|
+
'mmdc',
|
|
263
|
+
'-i', str(temp_mmd),
|
|
264
|
+
'-o', str(temp_svg_path),
|
|
265
|
+
'-b', 'transparent',
|
|
266
|
+
]
|
|
267
|
+
# Add config if provided
|
|
268
|
+
if config_path and config_path.exists():
|
|
269
|
+
svg_cmd.extend(['-c', str(config_path)])
|
|
270
|
+
svg_result = subprocess.run(svg_cmd, capture_output=True, text=True)
|
|
271
|
+
if svg_result.returncode == 0 and temp_svg_path.exists():
|
|
272
|
+
svg_content = temp_svg_path.read_text()
|
|
273
|
+
logical_width, logical_height = extract_svg_dimensions(svg_content)
|
|
274
|
+
|
|
275
|
+
# Build mmdc command for final output
|
|
276
|
+
# -w: width to fit diagrams on page
|
|
277
|
+
# -s: scale for higher resolution
|
|
278
|
+
# -b: transparent background
|
|
279
|
+
cmd = [
|
|
280
|
+
'mmdc',
|
|
281
|
+
'-i', str(temp_mmd),
|
|
282
|
+
'-o', str(output_path),
|
|
283
|
+
'-b', 'transparent',
|
|
284
|
+
'-w', str(width),
|
|
285
|
+
]
|
|
286
|
+
|
|
287
|
+
# Add config if provided (for consistent font sizing)
|
|
288
|
+
if config_path and config_path.exists():
|
|
289
|
+
cmd.extend(['-c', str(config_path)])
|
|
290
|
+
|
|
291
|
+
# Scale only applies to PNG (raster) output
|
|
292
|
+
if format == "png":
|
|
293
|
+
cmd.extend(['-s', str(scale)])
|
|
294
|
+
|
|
295
|
+
result = subprocess.run(cmd, capture_output=True, text=True)
|
|
296
|
+
|
|
297
|
+
# Check if rendering succeeded
|
|
298
|
+
if result.returncode != 0 or not output_path.exists():
|
|
299
|
+
raise RuntimeError(
|
|
300
|
+
f"Failed to render Mermaid diagram: {result.stderr}"
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
# Extract dimensions from SVG output if requested
|
|
304
|
+
if extract_dimensions and format == "svg":
|
|
305
|
+
svg_content = output_path.read_text()
|
|
306
|
+
logical_width, logical_height = extract_svg_dimensions(svg_content)
|
|
307
|
+
|
|
308
|
+
return output_path, logical_width, logical_height
|
|
309
|
+
finally:
|
|
310
|
+
# Clean up temporary files
|
|
311
|
+
if temp_mmd.exists():
|
|
312
|
+
temp_mmd.unlink()
|
|
313
|
+
if temp_svg_path and temp_svg_path.exists():
|
|
314
|
+
temp_svg_path.unlink()
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def render_all_diagrams(
|
|
318
|
+
markdown_content: str,
|
|
319
|
+
temp_dir: Path,
|
|
320
|
+
width: int = 1200,
|
|
321
|
+
scale: int = 2,
|
|
322
|
+
format: str = "png",
|
|
323
|
+
extract_dimensions: bool = False,
|
|
324
|
+
mermaid_config: Optional[Dict[str, Any]] = None
|
|
325
|
+
) -> Dict[str, DiagramInfo]:
|
|
326
|
+
"""Extract and render all Mermaid diagrams from markdown.
|
|
327
|
+
|
|
328
|
+
Args:
|
|
329
|
+
markdown_content: Markdown text containing Mermaid diagrams.
|
|
330
|
+
temp_dir: Directory to store rendered images.
|
|
331
|
+
width: Maximum width in pixels for diagrams (default: 1200).
|
|
332
|
+
scale: Scale factor for higher resolution (default: 2).
|
|
333
|
+
format: Output format - 'png' or 'svg' (default: 'png').
|
|
334
|
+
extract_dimensions: Whether to extract logical dimensions for consistent sizing.
|
|
335
|
+
mermaid_config: Optional Mermaid configuration dict for consistent styling.
|
|
336
|
+
If provided, will be written to a config file and passed to mmdc.
|
|
337
|
+
|
|
338
|
+
Returns:
|
|
339
|
+
Dictionary mapping original Mermaid code to DiagramInfo objects.
|
|
340
|
+
DiagramInfo contains the rendered path, optional title, and logical dimensions.
|
|
341
|
+
"""
|
|
342
|
+
blocks = extract_mermaid_blocks(markdown_content)
|
|
343
|
+
diagram_map = {}
|
|
344
|
+
|
|
345
|
+
# Write Mermaid config if provided
|
|
346
|
+
config_path = None
|
|
347
|
+
if mermaid_config:
|
|
348
|
+
config_path = write_mermaid_config(mermaid_config, temp_dir)
|
|
349
|
+
|
|
350
|
+
ext = 'svg' if format == 'svg' else 'png'
|
|
351
|
+
for idx, mermaid_code in enumerate(blocks):
|
|
352
|
+
# Extract title from diagram's YAML frontmatter
|
|
353
|
+
title, code_for_render = extract_diagram_title(mermaid_code)
|
|
354
|
+
|
|
355
|
+
output_path = temp_dir / f"diagram_{idx}.{ext}"
|
|
356
|
+
rendered_path, logical_width, logical_height = render_diagram(
|
|
357
|
+
code_for_render, output_path, width=width, scale=scale, format=format,
|
|
358
|
+
extract_dimensions=extract_dimensions, config_path=config_path
|
|
359
|
+
)
|
|
360
|
+
|
|
361
|
+
# Map original code (with frontmatter) to DiagramInfo
|
|
362
|
+
diagram_map[mermaid_code] = DiagramInfo(
|
|
363
|
+
path=rendered_path,
|
|
364
|
+
title=title,
|
|
365
|
+
code=mermaid_code,
|
|
366
|
+
logical_width=logical_width,
|
|
367
|
+
logical_height=logical_height,
|
|
368
|
+
units_per_inch=96.0 # Mermaid uses CSS pixels
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
return diagram_map
|