@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,332 @@
1
+ """Apply spacing configuration to DOCX documents.
2
+
3
+ Modifies paragraph spacing for headings, diagrams, and other elements
4
+ based on configuration from frontmatter or template.
5
+ """
6
+ import zipfile
7
+ import tempfile
8
+ import logging
9
+ from pathlib import Path
10
+ from typing import Optional
11
+
12
+ try:
13
+ from lxml import etree as ET
14
+ USING_LXML = True
15
+ except ImportError:
16
+ from xml.etree import ElementTree as ET
17
+ USING_LXML = False
18
+
19
+ from .spacing_config import SpacingConfig, ElementSpacing, DEFAULT_SPACING
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ # Word namespaces
24
+ NAMESPACES = {
25
+ 'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main',
26
+ 'r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
27
+ 'wp': 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing',
28
+ 'a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
29
+ 'pic': 'http://schemas.openxmlformats.org/drawingml/2006/picture',
30
+ 'v': 'urn:schemas-microsoft-com:vml',
31
+ 'o': 'urn:schemas-microsoft-com:office:office',
32
+ 'm': 'http://schemas.openxmlformats.org/officeDocument/2006/math',
33
+ 'w10': 'urn:schemas-microsoft-com:office:word',
34
+ }
35
+
36
+ W_NS = NAMESPACES['w']
37
+ W_PREFIX = '{' + W_NS + '}'
38
+
39
+ # Register all namespaces for ElementTree
40
+ if not USING_LXML:
41
+ for prefix, uri in NAMESPACES.items():
42
+ ET.register_namespace(prefix, uri)
43
+
44
+
45
+ def points_to_twips(points: int) -> int:
46
+ """Convert points to twips (1 point = 20 twips)."""
47
+ return points * 20
48
+
49
+
50
+ def apply_spacing_to_element(pPr, spacing: ElementSpacing) -> None:
51
+ """Apply spacing configuration to a paragraph properties element.
52
+
53
+ Args:
54
+ pPr: The w:pPr element to modify.
55
+ spacing: ElementSpacing configuration.
56
+ """
57
+ if spacing.before is None and spacing.after is None and spacing.line is None:
58
+ return
59
+
60
+ # Find or create w:spacing element
61
+ if USING_LXML:
62
+ spacing_elem = pPr.find('w:spacing', NAMESPACES)
63
+ else:
64
+ spacing_elem = pPr.find(f'{W_PREFIX}spacing')
65
+
66
+ if spacing_elem is None:
67
+ if USING_LXML:
68
+ spacing_elem = ET.SubElement(pPr, f'{{{W_NS}}}spacing')
69
+ else:
70
+ spacing_elem = ET.SubElement(pPr, f'{W_PREFIX}spacing')
71
+
72
+ # Apply spacing values (in twips)
73
+ if spacing.before is not None:
74
+ spacing_elem.set(f'{{{W_NS}}}before', str(points_to_twips(spacing.before)))
75
+ if spacing.after is not None:
76
+ spacing_elem.set(f'{{{W_NS}}}after', str(points_to_twips(spacing.after)))
77
+ if spacing.line is not None:
78
+ # Line spacing: 240 = single line, 360 = 1.5 lines, 480 = double
79
+ spacing_elem.set(f'{{{W_NS}}}line', str(int(spacing.line * 240)))
80
+ spacing_elem.set(f'{{{W_NS}}}lineRule', 'auto')
81
+
82
+
83
+ def get_heading_level(para) -> Optional[int]:
84
+ """Get heading level from paragraph style.
85
+
86
+ Args:
87
+ para: The w:p element.
88
+
89
+ Returns:
90
+ Heading level (1-6) or None if not a heading.
91
+ """
92
+ if USING_LXML:
93
+ pPr = para.find('w:pPr', NAMESPACES)
94
+ else:
95
+ pPr = para.find(f'{W_PREFIX}pPr')
96
+
97
+ if pPr is None:
98
+ return None
99
+
100
+ if USING_LXML:
101
+ pStyle = pPr.find('w:pStyle', NAMESPACES)
102
+ else:
103
+ pStyle = pPr.find(f'{W_PREFIX}pStyle')
104
+
105
+ if pStyle is None:
106
+ return None
107
+
108
+ style_val = pStyle.get(f'{{{W_NS}}}val', '')
109
+
110
+ # Check for Heading 1, Heading 2, etc.
111
+ if style_val.startswith('Heading'):
112
+ try:
113
+ level = int(style_val.replace('Heading', '').strip())
114
+ if 1 <= level <= 6:
115
+ return level
116
+ except ValueError:
117
+ pass
118
+
119
+ # Check for Heading1, Heading2, etc. (no space)
120
+ for i in range(1, 7):
121
+ if style_val == f'Heading{i}':
122
+ return i
123
+
124
+ return None
125
+
126
+
127
+ def is_diagram_paragraph(para) -> bool:
128
+ """Check if paragraph contains a diagram or image.
129
+
130
+ Args:
131
+ para: The w:p element.
132
+
133
+ Returns:
134
+ True if paragraph contains an image/diagram.
135
+ """
136
+ # Check for drawing elements (images, diagrams)
137
+ if USING_LXML:
138
+ drawings = para.findall('.//wp:drawing', NAMESPACES)
139
+ pics = para.findall('.//pic:pic', NAMESPACES)
140
+ picts = para.findall('.//v:shape', NAMESPACES)
141
+ else:
142
+ drawings = para.findall('.//{http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing}drawing')
143
+ pics = para.findall('.//{http://schemas.openxmlformats.org/drawingml/2006/picture}pic')
144
+ picts = para.findall('.//{urn:schemas-microsoft-com:vml}shape')
145
+
146
+ return bool(drawings or pics or picts)
147
+
148
+
149
+ def is_table_paragraph(para) -> bool:
150
+ """Check if paragraph is immediately before/after a table.
151
+
152
+ Note: Tables are w:tbl elements, not w:p. This function is for
153
+ identifying paragraphs that need spacing adjustment around tables.
154
+ """
155
+ # Tables are siblings, not children. This requires context.
156
+ return False
157
+
158
+
159
+ def is_code_block(para) -> bool:
160
+ """Check if paragraph is a code block.
161
+
162
+ Args:
163
+ para: The w:p element.
164
+
165
+ Returns:
166
+ True if paragraph is formatted as code.
167
+ """
168
+ if USING_LXML:
169
+ pPr = para.find('w:pPr', NAMESPACES)
170
+ else:
171
+ pPr = para.find(f'{W_PREFIX}pPr')
172
+
173
+ if pPr is None:
174
+ return False
175
+
176
+ if USING_LXML:
177
+ pStyle = pPr.find('w:pStyle', NAMESPACES)
178
+ else:
179
+ pStyle = pPr.find(f'{W_PREFIX}pStyle')
180
+
181
+ if pStyle is None:
182
+ return False
183
+
184
+ style_val = pStyle.get(f'{{{W_NS}}}val', '')
185
+ return style_val in ('SourceCode', 'Verbatim', 'Code', 'CodeBlock')
186
+
187
+
188
+ def apply_spacing_to_document(docx_path: Path, config: SpacingConfig) -> bool:
189
+ """Apply spacing configuration to a DOCX document.
190
+
191
+ Modifies paragraph spacing for headings, diagrams, and other elements.
192
+
193
+ Args:
194
+ docx_path: Path to the DOCX file.
195
+ config: SpacingConfig with spacing values.
196
+
197
+ Returns:
198
+ True if changes were made, False otherwise.
199
+ """
200
+ changes_made = False
201
+
202
+ with tempfile.TemporaryDirectory() as temp_dir:
203
+ temp_path = Path(temp_dir)
204
+
205
+ # Extract DOCX
206
+ with zipfile.ZipFile(docx_path, 'r') as zf:
207
+ zf.extractall(temp_path)
208
+
209
+ doc_xml_path = temp_path / 'word' / 'document.xml'
210
+ if not doc_xml_path.exists():
211
+ return False
212
+
213
+ # Parse document.xml - use lxml parser for proper namespace handling
214
+ if USING_LXML:
215
+ parser = ET.XMLParser(remove_blank_text=False)
216
+ tree = ET.parse(str(doc_xml_path), parser)
217
+ else:
218
+ tree = ET.parse(doc_xml_path)
219
+ root = tree.getroot()
220
+
221
+ # Find all paragraphs
222
+ if USING_LXML:
223
+ body = root.find('.//w:body', NAMESPACES)
224
+ else:
225
+ body = root.find(f'.//{W_PREFIX}body')
226
+
227
+ if body is None:
228
+ return False
229
+
230
+ elements = list(body)
231
+ prev_was_table = False
232
+
233
+ for i, elem in enumerate(elements):
234
+ # Handle tables - track for spacing on surrounding paragraphs
235
+ if elem.tag == f'{{{W_NS}}}tbl':
236
+ prev_was_table = True
237
+ continue
238
+
239
+ if elem.tag != f'{{{W_NS}}}p':
240
+ prev_was_table = False
241
+ continue
242
+
243
+ para = elem
244
+
245
+ # Get or create pPr
246
+ if USING_LXML:
247
+ pPr = para.find('w:pPr', NAMESPACES)
248
+ else:
249
+ pPr = para.find(f'{W_PREFIX}pPr')
250
+
251
+ if pPr is None:
252
+ if USING_LXML:
253
+ pPr = ET.Element(f'{{{W_NS}}}pPr')
254
+ else:
255
+ pPr = ET.Element(f'{W_PREFIX}pPr')
256
+ para.insert(0, pPr)
257
+
258
+ # Check element type and apply appropriate spacing
259
+ heading_level = get_heading_level(para)
260
+ if heading_level:
261
+ spacing = config.get_heading_spacing(heading_level)
262
+ if spacing:
263
+ apply_spacing_to_element(pPr, spacing)
264
+ changes_made = True
265
+ logger.debug(f"Applied H{heading_level} spacing: before={spacing.before}, after={spacing.after}")
266
+
267
+ elif is_diagram_paragraph(para):
268
+ if config.diagrams.before is not None or config.diagrams.after is not None:
269
+ apply_spacing_to_element(pPr, config.diagrams)
270
+ changes_made = True
271
+ logger.debug(f"Applied diagram spacing: before={config.diagrams.before}, after={config.diagrams.after}")
272
+
273
+ elif is_code_block(para):
274
+ if config.code_blocks.before is not None or config.code_blocks.after is not None:
275
+ apply_spacing_to_element(pPr, config.code_blocks)
276
+ changes_made = True
277
+
278
+ elif prev_was_table:
279
+ # Paragraph right after a table - apply table.after as before
280
+ if config.tables.after is not None:
281
+ # Create spacing with the table's after value as this paragraph's before
282
+ table_spacing = ElementSpacing(before=config.tables.after)
283
+ apply_spacing_to_element(pPr, table_spacing)
284
+ changes_made = True
285
+
286
+ prev_was_table = False
287
+
288
+ # Apply spacing to paragraphs before tables
289
+ for i, elem in enumerate(elements):
290
+ if elem.tag == f'{{{W_NS}}}tbl' and i > 0:
291
+ prev_elem = elements[i - 1]
292
+ if prev_elem.tag == f'{{{W_NS}}}p':
293
+ if USING_LXML:
294
+ pPr = prev_elem.find('w:pPr', NAMESPACES)
295
+ else:
296
+ pPr = prev_elem.find(f'{W_PREFIX}pPr')
297
+
298
+ if pPr is None:
299
+ if USING_LXML:
300
+ pPr = ET.Element(f'{{{W_NS}}}pPr')
301
+ else:
302
+ pPr = ET.Element(f'{W_PREFIX}pPr')
303
+ prev_elem.insert(0, pPr)
304
+ if config.tables.before is not None:
305
+ # Apply table.before as the paragraph's after
306
+ table_spacing = ElementSpacing(after=config.tables.before)
307
+ apply_spacing_to_element(pPr, table_spacing)
308
+ changes_made = True
309
+
310
+ if changes_made:
311
+ # Save modified document.xml
312
+ if USING_LXML:
313
+ tree.write(str(doc_xml_path), encoding='UTF-8', xml_declaration=True)
314
+ else:
315
+ tree.write(doc_xml_path, encoding='UTF-8', xml_declaration=True)
316
+
317
+ # Repackage DOCX - ensure [Content_Types].xml is first (Word requirement)
318
+ with zipfile.ZipFile(docx_path, 'w', zipfile.ZIP_DEFLATED) as zf:
319
+ # Write [Content_Types].xml first (required by OOXML spec)
320
+ content_types = temp_path / '[Content_Types].xml'
321
+ if content_types.exists():
322
+ zf.write(content_types, '[Content_Types].xml')
323
+
324
+ # Write remaining files
325
+ for file_path in sorted(temp_path.rglob('*')):
326
+ if file_path.is_file() and file_path.name != '[Content_Types].xml':
327
+ arcname = file_path.relative_to(temp_path)
328
+ zf.write(file_path, arcname)
329
+
330
+ logger.info("Applied spacing configuration to document")
331
+
332
+ return changes_made
@@ -0,0 +1,323 @@
1
+ """Spacing configuration module for headings and diagrams.
2
+
3
+ Provides dataclasses and functions for configuring paragraph spacing
4
+ for headings (H1-H6) and diagrams/images.
5
+
6
+ Frontmatter example:
7
+ ```yaml
8
+ spacing:
9
+ # Heading spacing (in points)
10
+ headings:
11
+ h1:
12
+ before: 24
13
+ after: 12
14
+ h2:
15
+ before: 18
16
+ after: 10
17
+ h3:
18
+ before: 14
19
+ after: 8
20
+ h4:
21
+ before: 12
22
+ after: 6
23
+ h5:
24
+ before: 10
25
+ after: 4
26
+ h6:
27
+ before: 8
28
+ after: 4
29
+ # Diagram/image spacing (in points)
30
+ diagrams:
31
+ before: 12
32
+ after: 12
33
+ # General paragraph spacing
34
+ paragraphs:
35
+ before: 0
36
+ after: 8
37
+ ```
38
+
39
+ Template config.yaml example:
40
+ ```yaml
41
+ spacing:
42
+ headings:
43
+ h1: { before: 24, after: 12 }
44
+ h2: { before: 18, after: 10 }
45
+ diagrams: { before: 12, after: 12 }
46
+ ```
47
+ """
48
+ from dataclasses import dataclass, field
49
+ from typing import Any, Dict, Optional
50
+ import logging
51
+
52
+ logger = logging.getLogger(__name__)
53
+
54
+
55
+ @dataclass
56
+ class ElementSpacing:
57
+ """Spacing configuration for a single element type.
58
+
59
+ Attributes:
60
+ before: Space before element in points.
61
+ after: Space after element in points.
62
+ line: Line spacing multiplier (1.0 = single, 1.5 = 1.5 lines, 2.0 = double).
63
+ """
64
+ before: Optional[int] = None
65
+ after: Optional[int] = None
66
+ line: Optional[float] = None
67
+
68
+ @classmethod
69
+ def from_dict(cls, data: Dict[str, Any]) -> 'ElementSpacing':
70
+ """Create ElementSpacing from a dictionary.
71
+
72
+ Args:
73
+ data: Dictionary with spacing properties.
74
+
75
+ Returns:
76
+ ElementSpacing instance.
77
+ """
78
+ if not data:
79
+ return cls()
80
+ return cls(
81
+ before=data.get('before'),
82
+ after=data.get('after'),
83
+ line=data.get('line'),
84
+ )
85
+
86
+
87
+ @dataclass
88
+ class SpacingConfig:
89
+ """Complete spacing configuration for document elements.
90
+
91
+ Attributes:
92
+ headings: Spacing for each heading level (h1-h6).
93
+ diagrams: Spacing for diagrams and images.
94
+ paragraphs: Default paragraph spacing.
95
+ tables: Spacing for tables.
96
+ code_blocks: Spacing for code blocks.
97
+ """
98
+ headings: Dict[str, ElementSpacing] = field(default_factory=dict)
99
+ diagrams: ElementSpacing = field(default_factory=ElementSpacing)
100
+ paragraphs: ElementSpacing = field(default_factory=ElementSpacing)
101
+ tables: ElementSpacing = field(default_factory=ElementSpacing)
102
+ code_blocks: ElementSpacing = field(default_factory=ElementSpacing)
103
+
104
+ @classmethod
105
+ def from_dict(cls, data: Dict[str, Any]) -> 'SpacingConfig':
106
+ """Create SpacingConfig from a dictionary.
107
+
108
+ Args:
109
+ data: Dictionary with spacing configuration.
110
+
111
+ Returns:
112
+ SpacingConfig instance.
113
+ """
114
+ if not data:
115
+ return cls()
116
+
117
+ # Parse headings
118
+ headings = {}
119
+ headings_data = data.get('headings', {})
120
+ for level in ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']:
121
+ if level in headings_data:
122
+ headings[level] = ElementSpacing.from_dict(headings_data[level])
123
+
124
+ # Parse other elements
125
+ diagrams = ElementSpacing.from_dict(data.get('diagrams', {}))
126
+ paragraphs = ElementSpacing.from_dict(data.get('paragraphs', {}))
127
+ tables = ElementSpacing.from_dict(data.get('tables', {}))
128
+ code_blocks = ElementSpacing.from_dict(data.get('code_blocks', {}))
129
+
130
+ return cls(
131
+ headings=headings,
132
+ diagrams=diagrams,
133
+ paragraphs=paragraphs,
134
+ tables=tables,
135
+ code_blocks=code_blocks,
136
+ )
137
+
138
+ def get_heading_spacing(self, level: int) -> Optional[ElementSpacing]:
139
+ """Get spacing for a specific heading level.
140
+
141
+ Args:
142
+ level: Heading level (1-6).
143
+
144
+ Returns:
145
+ ElementSpacing for the level, or None if not configured.
146
+ """
147
+ key = f'h{level}'
148
+ return self.headings.get(key)
149
+
150
+ def merge(self, override: 'SpacingConfig') -> 'SpacingConfig':
151
+ """Merge this config with an override config.
152
+
153
+ Override values take precedence.
154
+
155
+ Args:
156
+ override: SpacingConfig with override values.
157
+
158
+ Returns:
159
+ New SpacingConfig with merged values.
160
+ """
161
+ # Merge headings
162
+ merged_headings = {**self.headings}
163
+ for level, spacing in override.headings.items():
164
+ merged_headings[level] = spacing
165
+
166
+ # For other elements, use override if it has values
167
+ def merge_element(base: ElementSpacing, over: ElementSpacing) -> ElementSpacing:
168
+ return ElementSpacing(
169
+ before=over.before if over.before is not None else base.before,
170
+ after=over.after if over.after is not None else base.after,
171
+ line=over.line if over.line is not None else base.line,
172
+ )
173
+
174
+ return SpacingConfig(
175
+ headings=merged_headings,
176
+ diagrams=merge_element(self.diagrams, override.diagrams),
177
+ paragraphs=merge_element(self.paragraphs, override.paragraphs),
178
+ tables=merge_element(self.tables, override.tables),
179
+ code_blocks=merge_element(self.code_blocks, override.code_blocks),
180
+ )
181
+
182
+
183
+ # Default spacing configuration (in points)
184
+ DEFAULT_SPACING = SpacingConfig(
185
+ headings={
186
+ 'h1': ElementSpacing(before=24, after=12),
187
+ 'h2': ElementSpacing(before=18, after=10),
188
+ 'h3': ElementSpacing(before=14, after=8),
189
+ 'h4': ElementSpacing(before=12, after=6),
190
+ 'h5': ElementSpacing(before=10, after=4),
191
+ 'h6': ElementSpacing(before=8, after=4),
192
+ },
193
+ diagrams=ElementSpacing(before=12, after=12),
194
+ paragraphs=ElementSpacing(before=0, after=8),
195
+ tables=ElementSpacing(before=12, after=12),
196
+ code_blocks=ElementSpacing(before=8, after=8),
197
+ )
198
+
199
+
200
+ def extract_spacing_config(frontmatter: Dict[str, Any]) -> SpacingConfig:
201
+ """Extract spacing configuration from frontmatter.
202
+
203
+ Args:
204
+ frontmatter: Parsed frontmatter dictionary.
205
+
206
+ Returns:
207
+ SpacingConfig with values from frontmatter merged with defaults.
208
+ """
209
+ spacing_data = frontmatter.get('spacing', {})
210
+ if not spacing_data:
211
+ return DEFAULT_SPACING
212
+
213
+ user_config = SpacingConfig.from_dict(spacing_data)
214
+ return DEFAULT_SPACING.merge(user_config)
215
+
216
+
217
+ def load_template_spacing(template_path: 'Path') -> Optional[SpacingConfig]:
218
+ """Load spacing configuration from template.
219
+
220
+ Checks in order:
221
+ 1. config.yaml - YAML format spacing configuration
222
+ 2. styles.xml - Extract heading spacing from template styles
223
+
224
+ Args:
225
+ template_path: Path to template directory.
226
+
227
+ Returns:
228
+ SpacingConfig if spacing configuration found, None otherwise.
229
+ """
230
+ from pathlib import Path
231
+ import yaml
232
+
233
+ template_path = Path(template_path)
234
+
235
+ # First try config.yaml
236
+ config_file = template_path / 'config.yaml'
237
+ if config_file.exists():
238
+ try:
239
+ with open(config_file, 'r', encoding='utf-8') as f:
240
+ config = yaml.safe_load(f)
241
+ if config and 'spacing' in config:
242
+ return SpacingConfig.from_dict(config['spacing'])
243
+ except Exception as e:
244
+ logger.warning(f"Failed to load template config.yaml: {e}")
245
+
246
+ # Fall back to styles.xml
247
+ styles_file = template_path / 'styles.xml'
248
+ if styles_file.exists():
249
+ return load_spacing_from_styles_xml(styles_file)
250
+
251
+ return None
252
+
253
+
254
+ def load_spacing_from_styles_xml(styles_path: 'Path') -> Optional[SpacingConfig]:
255
+ """Load spacing configuration from template styles.xml.
256
+
257
+ Parses the styles.xml format used by template extractor to get
258
+ heading spacing values.
259
+
260
+ Args:
261
+ styles_path: Path to styles.xml file.
262
+
263
+ Returns:
264
+ SpacingConfig with heading spacing from styles.xml.
265
+ """
266
+ from pathlib import Path
267
+ from xml.etree import ElementTree as ET
268
+
269
+ try:
270
+ tree = ET.parse(styles_path)
271
+ root = tree.getroot()
272
+
273
+ headings = {}
274
+
275
+ # Find paragraph styles
276
+ para_styles = root.find('paragraph-styles')
277
+ if para_styles is None:
278
+ return None
279
+
280
+ # Map style names to heading levels
281
+ style_to_level = {
282
+ 'Heading 1': 'h1',
283
+ 'Heading 2': 'h2',
284
+ 'Heading 3': 'h3',
285
+ 'Heading 4': 'h4',
286
+ 'Heading 5': 'h5',
287
+ 'Heading 6': 'h6',
288
+ }
289
+
290
+ for style_elem in para_styles.findall('style'):
291
+ style_name = style_elem.get('name', '')
292
+ if style_name not in style_to_level:
293
+ continue
294
+
295
+ level_key = style_to_level[style_name]
296
+
297
+ # Get spacing element
298
+ spacing_elem = style_elem.find('spacing')
299
+ if spacing_elem is None:
300
+ continue
301
+
302
+ before_twips = spacing_elem.get('before')
303
+ after_twips = spacing_elem.get('after')
304
+ line = spacing_elem.get('line')
305
+
306
+ # Convert twips to points (20 twips = 1 point)
307
+ before_pts = int(int(before_twips) / 20) if before_twips else None
308
+ after_pts = int(int(after_twips) / 20) if after_twips else None
309
+ line_val = float(line) if line else None
310
+
311
+ headings[level_key] = ElementSpacing(
312
+ before=before_pts,
313
+ after=after_pts,
314
+ line=line_val,
315
+ )
316
+
317
+ if headings:
318
+ return SpacingConfig(headings=headings)
319
+
320
+ except Exception as e:
321
+ logger.warning(f"Failed to load spacing from styles.xml: {e}")
322
+
323
+ return None