@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.
Files changed (72) hide show
  1. package/.pi/skills/document-converter/SKILL.md +79 -0
  2. package/README.md +106 -0
  3. package/engine/.dockerignore +4 -0
  4. package/engine/Dockerfile +75 -0
  5. package/engine/IMAGE_VERSION +1 -0
  6. package/engine/README.md +65 -0
  7. package/engine/VENDOR.md +40 -0
  8. package/engine/build-image.sh +29 -0
  9. package/engine/document_converter/LICENSE +21 -0
  10. package/engine/document_converter/__init__.py +365 -0
  11. package/engine/document_converter/__main__.py +5 -0
  12. package/engine/document_converter/asciidoc_converter.py +534 -0
  13. package/engine/document_converter/cli.py +751 -0
  14. package/engine/document_converter/code_renderer.py +356 -0
  15. package/engine/document_converter/converter.py +928 -0
  16. package/engine/document_converter/cover_page.py +448 -0
  17. package/engine/document_converter/diagram_resizer.py +311 -0
  18. package/engine/document_converter/diagram_sizing.py +357 -0
  19. package/engine/document_converter/docx_reader.py +627 -0
  20. package/engine/document_converter/field_updater.py +277 -0
  21. package/engine/document_converter/font_manager.py +850 -0
  22. package/engine/document_converter/frontmatter_parser.py +644 -0
  23. package/engine/document_converter/graphviz_renderer.py +354 -0
  24. package/engine/document_converter/image_extractor.py +281 -0
  25. package/engine/document_converter/image_style.py +237 -0
  26. package/engine/document_converter/logo_manager.py +1021 -0
  27. package/engine/document_converter/manifest_manager.py +288 -0
  28. package/engine/document_converter/mermaid_renderer.py +371 -0
  29. package/engine/document_converter/meta_mapper.py +398 -0
  30. package/engine/document_converter/pandoc_styles.py +222 -0
  31. package/engine/document_converter/pdf_converter.py +735 -0
  32. package/engine/document_converter/pdf_server.py +283 -0
  33. package/engine/document_converter/plantuml_renderer.py +460 -0
  34. package/engine/document_converter/plantuml_server.py +273 -0
  35. package/engine/document_converter/pyproject.toml +80 -0
  36. package/engine/document_converter/round_trip.py +312 -0
  37. package/engine/document_converter/spacing_applier.py +332 -0
  38. package/engine/document_converter/spacing_config.py +323 -0
  39. package/engine/document_converter/style_extractor.py +420 -0
  40. package/engine/document_converter/svg_embedder.py +294 -0
  41. package/engine/document_converter/system_variables.py +158 -0
  42. package/engine/document_converter/table_formatter.py +450 -0
  43. package/engine/document_converter/template_extractor.py +1334 -0
  44. package/engine/document_converter/template_manager.py +427 -0
  45. package/engine/document_converter/textbox_extractor.py +551 -0
  46. package/engine/document_converter/toc_generator.py +559 -0
  47. package/engine/document_converter/toc_style.py +290 -0
  48. package/engine/document_converter/tree_renderer.py +328 -0
  49. package/engine/document_converter/utils.py +134 -0
  50. package/engine/document_converter/variable_manager.py +394 -0
  51. package/engine/engine_cli.py +371 -0
  52. package/engine/frontmatter_filler/doc-meta.sample.yaml +106 -0
  53. package/engine/frontmatter_filler/fill.py +517 -0
  54. package/engine/markdown_table_profiler/profile.py +442 -0
  55. package/engine/nano-banana-styles.yaml +59 -0
  56. package/engine/tests/test_styled_diagrams.py +109 -0
  57. package/package.json +32 -0
  58. package/src/__tests__/engine.test.ts +72 -0
  59. package/src/__tests__/facade.test.ts +120 -0
  60. package/src/__tests__/integration.test.ts +101 -0
  61. package/src/__tests__/ocr.test.ts +34 -0
  62. package/src/__tests__/provenance.test.ts +89 -0
  63. package/src/__tests__/routing.test.ts +40 -0
  64. package/src/engine.ts +187 -0
  65. package/src/errors.ts +43 -0
  66. package/src/index.ts +179 -0
  67. package/src/ocr.ts +43 -0
  68. package/src/provenance.ts +79 -0
  69. package/src/routing.ts +49 -0
  70. package/src/schema.json +69 -0
  71. package/src/schema.ts +107 -0
  72. package/src/types.ts +90 -0
@@ -0,0 +1,311 @@
1
+ """Apply calculated diagram dimensions to images in DOCX files.
2
+
3
+ This module resizes diagram images in the generated DOCX to match the
4
+ dimensions calculated by the Constant Zoom normalization algorithm.
5
+ """
6
+ import hashlib
7
+ import re
8
+ import zipfile
9
+ import tempfile
10
+ import logging
11
+ from pathlib import Path
12
+ from typing import Dict, List, Tuple
13
+ from dataclasses import dataclass
14
+
15
+ from .diagram_sizing import DiagramDimensions, SizingConfig, calculate_diagram_dimensions
16
+ from .mermaid_renderer import DiagramInfo
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ @dataclass
22
+ class ImageSizeMapping:
23
+ """Mapping of image content hash to calculated dimensions."""
24
+ content_hash: str
25
+ dimensions: DiagramDimensions
26
+ source_path: Path # Original path for logging
27
+
28
+
29
+ def _compute_file_hash(file_path: Path) -> str:
30
+ """Compute MD5 hash of file content."""
31
+ hasher = hashlib.md5()
32
+ with open(file_path, 'rb') as f:
33
+ for chunk in iter(lambda: f.read(8192), b''):
34
+ hasher.update(chunk)
35
+ return hasher.hexdigest()
36
+
37
+
38
+ def build_diagram_size_map(
39
+ mermaid_diagrams: Dict[str, DiagramInfo],
40
+ plantuml_diagrams: List[DiagramInfo],
41
+ graphviz_diagrams: Dict[str, DiagramInfo],
42
+ sizing_config: SizingConfig
43
+ ) -> Dict[str, Tuple[DiagramDimensions, str]]:
44
+ """Build mapping from image content hashes to calculated dimensions.
45
+
46
+ Args:
47
+ mermaid_diagrams: Dictionary of mermaid code -> DiagramInfo.
48
+ plantuml_diagrams: List of PlantUML DiagramInfo objects.
49
+ graphviz_diagrams: Dictionary of graphviz code -> DiagramInfo.
50
+ sizing_config: Configuration for diagram sizing.
51
+
52
+ Returns:
53
+ Dictionary mapping content hash to (DiagramDimensions, source_filename).
54
+ """
55
+ size_map: Dict[str, Tuple[DiagramDimensions, str]] = {}
56
+
57
+ # Process Mermaid diagrams
58
+ for mermaid_code, diagram_info in mermaid_diagrams.items():
59
+ if diagram_info.path and diagram_info.path.exists():
60
+ if diagram_info.logical_width and diagram_info.logical_height:
61
+ dims = calculate_diagram_dimensions(
62
+ diagram_info.logical_width,
63
+ diagram_info.logical_height,
64
+ diagram_info.units_per_inch,
65
+ sizing_config
66
+ )
67
+ content_hash = _compute_file_hash(diagram_info.path)
68
+ size_map[content_hash] = (dims, diagram_info.path.name)
69
+ logger.debug(f"Mermaid {diagram_info.path.name}: {dims.width_inches:.2f}x{dims.height_inches:.2f} in")
70
+
71
+ # Process PlantUML diagrams
72
+ for diagram_info in plantuml_diagrams:
73
+ if diagram_info.path and diagram_info.path.exists():
74
+ if diagram_info.logical_width and diagram_info.logical_height:
75
+ dims = calculate_diagram_dimensions(
76
+ diagram_info.logical_width,
77
+ diagram_info.logical_height,
78
+ diagram_info.units_per_inch,
79
+ sizing_config
80
+ )
81
+ content_hash = _compute_file_hash(diagram_info.path)
82
+ size_map[content_hash] = (dims, diagram_info.path.name)
83
+ logger.debug(f"PlantUML {diagram_info.path.name}: {dims.width_inches:.2f}x{dims.height_inches:.2f} in")
84
+
85
+ # Process Graphviz diagrams
86
+ for graphviz_code, diagram_info in graphviz_diagrams.items():
87
+ if diagram_info.path and diagram_info.path.exists():
88
+ if diagram_info.logical_width and diagram_info.logical_height:
89
+ dims = calculate_diagram_dimensions(
90
+ diagram_info.logical_width,
91
+ diagram_info.logical_height,
92
+ diagram_info.units_per_inch,
93
+ sizing_config
94
+ )
95
+ content_hash = _compute_file_hash(diagram_info.path)
96
+ size_map[content_hash] = (dims, diagram_info.path.name)
97
+ logger.debug(f"Graphviz {diagram_info.path.name}: {dims.width_inches:.2f}x{dims.height_inches:.2f} in")
98
+
99
+ return size_map
100
+
101
+
102
+ def apply_diagram_sizes(
103
+ docx_path: Path,
104
+ size_map: Dict[str, Tuple[DiagramDimensions, str]]
105
+ ) -> int:
106
+ """Apply calculated dimensions to diagram images in DOCX.
107
+
108
+ Matches images by content hash to handle pandoc renaming files.
109
+
110
+ Args:
111
+ docx_path: Path to the DOCX file to modify.
112
+ size_map: Dictionary mapping content hash to (DiagramDimensions, source_filename).
113
+
114
+ Returns:
115
+ Number of images resized.
116
+ """
117
+ if not size_map:
118
+ return 0
119
+
120
+ resized_count = 0
121
+
122
+ # Extract DOCX to temp directory
123
+ with tempfile.TemporaryDirectory() as temp_dir:
124
+ temp_path = Path(temp_dir)
125
+
126
+ # Extract the docx
127
+ with zipfile.ZipFile(docx_path, 'r') as zf:
128
+ zf.extractall(temp_path)
129
+
130
+ # Read relationships to map image filenames to relationship IDs
131
+ rels_path = temp_path / 'word' / '_rels' / 'document.xml.rels'
132
+ if not rels_path.exists():
133
+ logger.warning("No document.xml.rels found")
134
+ return 0
135
+
136
+ rels_content = rels_path.read_text(encoding='utf-8')
137
+
138
+ # Read document.xml
139
+ doc_xml_path = temp_path / 'word' / 'document.xml'
140
+ if not doc_xml_path.exists():
141
+ logger.warning("No document.xml found")
142
+ return 0
143
+
144
+ doc_content = doc_xml_path.read_text(encoding='utf-8')
145
+
146
+ # Build mapping from rId to filename in DOCX
147
+ rid_to_filename: Dict[str, str] = {}
148
+ rel_pattern = r'<Relationship[^>]*Id="([^"]+)"[^>]*Target="media/([^"]+)"'
149
+ for match in re.finditer(rel_pattern, rels_content):
150
+ rid = match.group(1)
151
+ filename = match.group(2)
152
+ rid_to_filename[rid] = filename
153
+
154
+ # Also try alternate attribute order
155
+ rel_pattern2 = r'<Relationship[^>]*Target="media/([^"]+)"[^>]*Id="([^"]+)"'
156
+ for match in re.finditer(rel_pattern2, rels_content):
157
+ filename = match.group(1)
158
+ rid = match.group(2)
159
+ if rid not in rid_to_filename:
160
+ rid_to_filename[rid] = filename
161
+
162
+ # Build hash-to-dimensions map for images in DOCX
163
+ media_dir = temp_path / 'word' / 'media'
164
+ if not media_dir.exists():
165
+ logger.debug("No media directory in DOCX")
166
+ return 0
167
+
168
+ # Map DOCX image filenames to their hashes
169
+ docx_file_to_hash: Dict[str, str] = {}
170
+ for img_file in media_dir.iterdir():
171
+ if img_file.is_file():
172
+ docx_file_to_hash[img_file.name] = _compute_file_hash(img_file)
173
+
174
+ # Find which DOCX images match our source diagrams
175
+ docx_file_to_dims: Dict[str, DiagramDimensions] = {}
176
+ for docx_filename, img_hash in docx_file_to_hash.items():
177
+ if img_hash in size_map:
178
+ dims, source_name = size_map[img_hash]
179
+ docx_file_to_dims[docx_filename] = dims
180
+ logger.debug(f"Matched {source_name} -> {docx_filename}")
181
+
182
+ # Collect all rIds that need to be resized for centering pass
183
+ rids_to_resize = set()
184
+ for rid, filename in rid_to_filename.items():
185
+ if filename in docx_file_to_dims:
186
+ rids_to_resize.add(rid)
187
+
188
+ # Find and update each matched diagram image
189
+ modified = False
190
+ for rid, filename in rid_to_filename.items():
191
+ if filename not in docx_file_to_dims:
192
+ continue
193
+
194
+ dims = docx_file_to_dims[filename]
195
+ logger.info(f"Resizing {filename} to {dims.width_inches:.2f}x{dims.height_inches:.2f} in")
196
+
197
+ # Find the drawing element with this relationship ID
198
+ # Pattern: <w:drawing>...<a:blip r:embed="rId..."/>...</w:drawing>
199
+ drawing_pattern = rf'(<w:drawing>)((?:(?!</w:drawing>).)*r:embed="{rid}"(?:(?!</w:drawing>).)*)(</w:drawing>)'
200
+
201
+ def replace_dimensions(match):
202
+ nonlocal modified, resized_count
203
+ drawing_start = match.group(1)
204
+ drawing_content = match.group(2)
205
+ drawing_end = match.group(3)
206
+
207
+ # Update wp:extent cx="..." cy="..."
208
+ new_content = re.sub(
209
+ r'(<wp:extent\s+)cx="(\d+)"\s+cy="(\d+)"',
210
+ rf'\1cx="{dims.width_emu}" cy="{dims.height_emu}"',
211
+ drawing_content
212
+ )
213
+
214
+ # Update a:ext cx="..." cy="..." (inside a:xfrm)
215
+ new_content = re.sub(
216
+ r'(<a:ext\s+)cx="(\d+)"\s+cy="(\d+)"',
217
+ rf'\1cx="{dims.width_emu}" cy="{dims.height_emu}"',
218
+ new_content
219
+ )
220
+
221
+ if new_content != drawing_content:
222
+ modified = True
223
+ resized_count += 1
224
+
225
+ return f'{drawing_start}{new_content}{drawing_end}'
226
+
227
+ doc_content = re.sub(drawing_pattern, replace_dimensions, doc_content, flags=re.DOTALL)
228
+
229
+ # Center-align paragraphs containing diagram images
230
+ if rids_to_resize:
231
+ doc_content = _center_diagram_paragraphs(doc_content, rids_to_resize)
232
+ modified = True
233
+
234
+ if modified:
235
+ # Write modified document.xml
236
+ doc_xml_path.write_text(doc_content, encoding='utf-8')
237
+
238
+ # Repack the DOCX
239
+ _repack_docx(temp_path, docx_path)
240
+
241
+ return resized_count
242
+
243
+
244
+ def _center_diagram_paragraphs(doc_content: str, rids: set) -> str:
245
+ """Center-align paragraphs containing diagram images.
246
+
247
+ Args:
248
+ doc_content: The document.xml content.
249
+ rids: Set of relationship IDs for diagram images.
250
+
251
+ Returns:
252
+ Modified document content with centered diagram paragraphs.
253
+ """
254
+ # Word namespace
255
+ w_ns = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'
256
+
257
+ # Build pattern to match any of the diagram rIds
258
+ rid_pattern = '|'.join(re.escape(rid) for rid in rids)
259
+
260
+ # Find paragraphs containing drawings with our rIds
261
+ # Pattern: <w:p>...<w:drawing>...<a:blip r:embed="rIdX"/>...</w:drawing>...</w:p>
262
+ para_pattern = rf'(<w:p[^>]*>)((?:(?!</w:p>).)*<w:drawing>(?:(?!</w:drawing>).)*r:embed="({rid_pattern})"(?:(?!</w:drawing>).)*</w:drawing>(?:(?!</w:p>).)*)(</w:p>)'
263
+
264
+ def add_center_alignment(match):
265
+ para_start = match.group(1)
266
+ para_content = match.group(2)
267
+ para_end = match.group(4)
268
+
269
+ # Check if paragraph already has w:pPr
270
+ if '<w:pPr>' in para_content or '<w:pPr ' in para_content:
271
+ # Check if it already has w:jc
272
+ if f'<w:jc ' in para_content:
273
+ # Update existing w:jc to center
274
+ para_content = re.sub(
275
+ r'<w:jc\s+w:val="[^"]*"',
276
+ f'<w:jc w:val="center"',
277
+ para_content
278
+ )
279
+ else:
280
+ # Add w:jc inside existing w:pPr
281
+ para_content = re.sub(
282
+ r'(<w:pPr[^>]*>)',
283
+ rf'\1<w:jc w:val="center"/>',
284
+ para_content
285
+ )
286
+ else:
287
+ # No w:pPr exists, add it after para_start
288
+ # Insert right after <w:p> or <w:p ...>
289
+ para_content = f'<w:pPr><w:jc w:val="center"/></w:pPr>{para_content}'
290
+
291
+ return f'{para_start}{para_content}{para_end}'
292
+
293
+ return re.sub(para_pattern, add_center_alignment, doc_content, flags=re.DOTALL)
294
+
295
+
296
+ def _repack_docx(extracted_dir: Path, output_path: Path) -> None:
297
+ """Repack extracted DOCX contents into a DOCX file.
298
+
299
+ Args:
300
+ extracted_dir: Directory containing extracted DOCX contents.
301
+ output_path: Path to write the repacked DOCX.
302
+ """
303
+ # Remove existing file
304
+ if output_path.exists():
305
+ output_path.unlink()
306
+
307
+ with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zf:
308
+ for file_path in extracted_dir.rglob('*'):
309
+ if file_path.is_file():
310
+ arcname = file_path.relative_to(extracted_dir)
311
+ zf.write(file_path, arcname)
@@ -0,0 +1,357 @@
1
+ """Diagram sizing algorithm for consistent visual scaling.
2
+
3
+ This module implements the Constant Zoom normalization algorithm that ensures
4
+ diagrams from different tools (Mermaid, PlantUML, Graphviz) appear with
5
+ consistent visual scale in the output document.
6
+
7
+ The algorithm:
8
+ 1. Extracts logical dimensions from diagram source (SVG viewBox, JSON bounding box)
9
+ 2. Converts to physical dimensions using units_per_inch (96 for CSS pixels, 72 for points)
10
+ 3. Calculates scale factor to fit within page constraints
11
+ 4. Applies minimum scale threshold to prevent unreadable diagrams
12
+ 5. Optionally rotates wide diagrams to landscape orientation
13
+ """
14
+ from dataclasses import dataclass
15
+ from enum import Enum
16
+ from typing import Optional, Tuple
17
+ import logging
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ # Default page dimensions (Letter size with 1" margins)
22
+ DEFAULT_PAGE_WIDTH_INCHES = 6.5 # 8.5" - 2" margins
23
+ DEFAULT_PAGE_HEIGHT_INCHES = 9.0 # 11" - 2" margins
24
+
25
+ # Minimum scale threshold (30% of original size)
26
+ DEFAULT_MIN_SCALE = 0.3
27
+
28
+ # EMU (English Metric Units) per inch for python-docx
29
+ EMU_PER_INCH = 914400
30
+
31
+
32
+ class SizingMode(Enum):
33
+ """Diagram sizing mode."""
34
+ FIXED = "fixed" # Use fixed dimensions (legacy behavior)
35
+ CONSISTENT = "consistent" # Use Constant Zoom normalization
36
+ AUTO = "auto" # Automatic based on diagram complexity
37
+
38
+
39
+ class RotationMode(Enum):
40
+ """Rotation mode for wide diagrams."""
41
+ NONE = "none" # Never rotate
42
+ AUTO = "auto" # Auto-rotate if it improves fit
43
+ WARN = "warn" # Warn user about rotation opportunity
44
+
45
+
46
+ @dataclass
47
+ class SizingConfig:
48
+ """Configuration for diagram sizing.
49
+
50
+ Attributes:
51
+ mode: Sizing mode (fixed, consistent, auto).
52
+ page_width_inches: Available width on page in inches.
53
+ page_height_inches: Available height on page in inches.
54
+ min_scale: Minimum scale factor (0.3 = 30% of original).
55
+ rotation: Rotation mode for wide diagrams.
56
+ default_dpi: Default DPI for diagrams without dimension info.
57
+ """
58
+ mode: SizingMode = SizingMode.CONSISTENT
59
+ page_width_inches: float = DEFAULT_PAGE_WIDTH_INCHES
60
+ page_height_inches: float = DEFAULT_PAGE_HEIGHT_INCHES
61
+ min_scale: float = DEFAULT_MIN_SCALE
62
+ rotation: RotationMode = RotationMode.WARN
63
+ default_dpi: int = 96
64
+
65
+
66
+ @dataclass
67
+ class DiagramDimensions:
68
+ """Calculated dimensions for a diagram.
69
+
70
+ Attributes:
71
+ width_inches: Final width in inches.
72
+ height_inches: Final height in inches.
73
+ width_emu: Final width in EMU (for python-docx).
74
+ height_emu: Final height in EMU (for python-docx).
75
+ scale_factor: Applied scale factor (1.0 = original size).
76
+ rotation_applied: Whether diagram was rotated.
77
+ rotation_recommended: Whether rotation would improve fit.
78
+ warning: Optional warning message.
79
+ """
80
+ width_inches: float
81
+ height_inches: float
82
+ width_emu: int
83
+ height_emu: int
84
+ scale_factor: float
85
+ rotation_applied: bool = False
86
+ rotation_recommended: bool = False
87
+ warning: Optional[str] = None
88
+
89
+
90
+ def calculate_diagram_dimensions(
91
+ logical_width: Optional[float],
92
+ logical_height: Optional[float],
93
+ units_per_inch: float = 96.0,
94
+ config: Optional[SizingConfig] = None
95
+ ) -> DiagramDimensions:
96
+ """Calculate final diagram dimensions using Constant Zoom algorithm.
97
+
98
+ Args:
99
+ logical_width: Logical width in source units (CSS pixels or points).
100
+ logical_height: Logical height in source units.
101
+ units_per_inch: Conversion factor (96 for CSS pixels, 72 for points).
102
+ config: Sizing configuration. Uses defaults if not provided.
103
+
104
+ Returns:
105
+ DiagramDimensions with calculated sizes and metadata.
106
+ """
107
+ if config is None:
108
+ config = SizingConfig()
109
+
110
+ # Handle missing dimensions
111
+ if logical_width is None or logical_height is None:
112
+ # Fall back to default size that fits page width
113
+ return DiagramDimensions(
114
+ width_inches=config.page_width_inches,
115
+ height_inches=config.page_width_inches * 0.75, # 4:3 aspect ratio default
116
+ width_emu=int(config.page_width_inches * EMU_PER_INCH),
117
+ height_emu=int(config.page_width_inches * 0.75 * EMU_PER_INCH),
118
+ scale_factor=1.0,
119
+ warning="Diagram dimensions not available, using default size"
120
+ )
121
+
122
+ # Convert logical units to inches
123
+ width_inches = logical_width / units_per_inch
124
+ height_inches = logical_height / units_per_inch
125
+
126
+ # For fixed mode, just return the natural size (clamped to page)
127
+ if config.mode == SizingMode.FIXED:
128
+ return _calculate_fixed_dimensions(
129
+ width_inches, height_inches, config
130
+ )
131
+
132
+ # For consistent mode, apply Constant Zoom normalization
133
+ return _calculate_consistent_dimensions(
134
+ width_inches, height_inches, config
135
+ )
136
+
137
+
138
+ def _calculate_fixed_dimensions(
139
+ width_inches: float,
140
+ height_inches: float,
141
+ config: SizingConfig
142
+ ) -> DiagramDimensions:
143
+ """Calculate dimensions using fixed mode (scale to fit page only).
144
+
145
+ Args:
146
+ width_inches: Natural width in inches.
147
+ height_inches: Natural height in inches.
148
+ config: Sizing configuration.
149
+
150
+ Returns:
151
+ DiagramDimensions scaled to fit page.
152
+ """
153
+ # Calculate scale to fit within page bounds
154
+ width_scale = config.page_width_inches / width_inches if width_inches > 0 else 1.0
155
+ height_scale = config.page_height_inches / height_inches if height_inches > 0 else 1.0
156
+
157
+ # Use the smaller scale to fit both dimensions
158
+ scale = min(width_scale, height_scale, 1.0) # Don't upscale
159
+
160
+ final_width = width_inches * scale
161
+ final_height = height_inches * scale
162
+
163
+ return DiagramDimensions(
164
+ width_inches=final_width,
165
+ height_inches=final_height,
166
+ width_emu=int(final_width * EMU_PER_INCH),
167
+ height_emu=int(final_height * EMU_PER_INCH),
168
+ scale_factor=scale
169
+ )
170
+
171
+
172
+ def _calculate_consistent_dimensions(
173
+ width_inches: float,
174
+ height_inches: float,
175
+ config: SizingConfig
176
+ ) -> DiagramDimensions:
177
+ """Calculate dimensions using Constant Zoom normalization.
178
+
179
+ This algorithm ensures that all diagrams are rendered at a consistent
180
+ zoom level relative to the page, so a 10pt font in one diagram appears
181
+ the same size as a 10pt font in another diagram.
182
+
183
+ Args:
184
+ width_inches: Natural width in inches.
185
+ height_inches: Natural height in inches.
186
+ config: Sizing configuration.
187
+
188
+ Returns:
189
+ DiagramDimensions with consistent scaling applied.
190
+ """
191
+ # Calculate scale factors for width and height
192
+ width_scale = config.page_width_inches / width_inches if width_inches > 0 else 1.0
193
+ height_scale = config.page_height_inches / height_inches if height_inches > 0 else 1.0
194
+
195
+ # Use the smaller scale to fit both dimensions
196
+ scale = min(width_scale, height_scale)
197
+
198
+ # Check if rotation would improve the fit
199
+ rotation_recommended = False
200
+ rotated_scale = None
201
+
202
+ # Minimum improvement threshold for rotation (20% better fit required)
203
+ # This prevents rotating diagrams that are only slightly wider than tall
204
+ ROTATION_IMPROVEMENT_THRESHOLD = 0.20
205
+
206
+ if width_inches > height_inches:
207
+ # Wide diagram - check if rotation improves fit
208
+ rotated_width_scale = config.page_width_inches / height_inches if height_inches > 0 else 1.0
209
+ rotated_height_scale = config.page_height_inches / width_inches if width_inches > 0 else 1.0
210
+ rotated_scale = min(rotated_width_scale, rotated_height_scale)
211
+
212
+ # Only recommend rotation if it provides significant improvement
213
+ improvement = (rotated_scale / scale - 1) if scale > 0 else 0
214
+ if rotated_scale > scale and improvement >= ROTATION_IMPROVEMENT_THRESHOLD:
215
+ rotation_recommended = True
216
+
217
+ # Handle rotation recommendation
218
+ # NOTE: We do NOT swap dimensions here because that would distort the image.
219
+ # The rotation_applied/rotation_recommended flags are informational only.
220
+ # Actual image rotation would require rotating the PNG/SVG file itself,
221
+ # which is not implemented. For now, we just warn about the opportunity.
222
+ rotation_applied = False
223
+ warning = None
224
+
225
+ if rotation_recommended:
226
+ improvement = (rotated_scale / scale - 1) * 100 if scale > 0 else 0
227
+ if config.rotation == RotationMode.AUTO or config.rotation == RotationMode.WARN:
228
+ # Don't actually rotate - just warn about the opportunity
229
+ # Swapping dimensions without rotating the image causes distortion
230
+ warning = (
231
+ f"Diagram would fit {improvement:.0f}% larger if rotated to landscape. "
232
+ f"Consider restructuring the diagram to be taller than wide."
233
+ )
234
+
235
+ # Check minimum scale threshold
236
+ if scale < config.min_scale:
237
+ warning_msg = (
238
+ f"Diagram scaled to {scale:.0%} which is below minimum threshold "
239
+ f"({config.min_scale:.0%}). Diagram may be difficult to read."
240
+ )
241
+ if warning:
242
+ warning = f"{warning} {warning_msg}"
243
+ else:
244
+ warning = warning_msg
245
+
246
+ # Log the warning
247
+ logger.warning(warning_msg)
248
+
249
+ # Don't upscale diagrams
250
+ scale = min(scale, 1.0)
251
+
252
+ final_width = width_inches * scale
253
+ final_height = height_inches * scale
254
+
255
+ return DiagramDimensions(
256
+ width_inches=final_width,
257
+ height_inches=final_height,
258
+ width_emu=int(final_width * EMU_PER_INCH),
259
+ height_emu=int(final_height * EMU_PER_INCH),
260
+ scale_factor=scale,
261
+ rotation_applied=rotation_applied,
262
+ rotation_recommended=rotation_recommended,
263
+ warning=warning
264
+ )
265
+
266
+
267
+ def inches_to_emu(inches: float) -> int:
268
+ """Convert inches to EMU (English Metric Units).
269
+
270
+ Args:
271
+ inches: Dimension in inches.
272
+
273
+ Returns:
274
+ Dimension in EMU.
275
+ """
276
+ return int(inches * EMU_PER_INCH)
277
+
278
+
279
+ def emu_to_inches(emu: int) -> float:
280
+ """Convert EMU (English Metric Units) to inches.
281
+
282
+ Args:
283
+ emu: Dimension in EMU.
284
+
285
+ Returns:
286
+ Dimension in inches.
287
+ """
288
+ return emu / EMU_PER_INCH
289
+
290
+
291
+ def parse_sizing_config(frontmatter: dict) -> SizingConfig:
292
+ """Parse sizing configuration from document frontmatter.
293
+
294
+ Expected frontmatter format:
295
+ ```yaml
296
+ diagrams:
297
+ sizing: consistent # or fixed, auto
298
+ min_scale: 0.3
299
+ rotation: warn # or auto, none
300
+ page_width: 6.5 # inches
301
+ page_height: 9.0 # inches
302
+ ```
303
+
304
+ Args:
305
+ frontmatter: Parsed frontmatter dictionary.
306
+
307
+ Returns:
308
+ SizingConfig with parsed values or defaults.
309
+ """
310
+ config = SizingConfig()
311
+
312
+ diagrams = frontmatter.get('diagrams', {})
313
+ if not isinstance(diagrams, dict):
314
+ return config
315
+
316
+ # Parse sizing mode
317
+ sizing = diagrams.get('sizing', 'consistent')
318
+ if sizing == 'fixed':
319
+ config.mode = SizingMode.FIXED
320
+ elif sizing == 'auto':
321
+ config.mode = SizingMode.AUTO
322
+ else:
323
+ config.mode = SizingMode.CONSISTENT
324
+
325
+ # Parse min_scale
326
+ min_scale = diagrams.get('min_scale')
327
+ if min_scale is not None:
328
+ try:
329
+ config.min_scale = float(min_scale)
330
+ except (TypeError, ValueError):
331
+ pass
332
+
333
+ # Parse rotation mode
334
+ rotation = diagrams.get('rotation', 'warn')
335
+ if rotation == 'auto':
336
+ config.rotation = RotationMode.AUTO
337
+ elif rotation == 'none':
338
+ config.rotation = RotationMode.NONE
339
+ else:
340
+ config.rotation = RotationMode.WARN
341
+
342
+ # Parse page dimensions
343
+ page_width = diagrams.get('page_width')
344
+ if page_width is not None:
345
+ try:
346
+ config.page_width_inches = float(page_width)
347
+ except (TypeError, ValueError):
348
+ pass
349
+
350
+ page_height = diagrams.get('page_height')
351
+ if page_height is not None:
352
+ try:
353
+ config.page_height_inches = float(page_height)
354
+ except (TypeError, ValueError):
355
+ pass
356
+
357
+ return config