@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,427 @@
1
+ """Template management for DOCX documents."""
2
+ from pathlib import Path
3
+ from typing import Optional, List, Dict, Any
4
+ from xml.etree import ElementTree as ET
5
+ from docx import Document
6
+ import shutil
7
+ import re
8
+
9
+
10
+ def _find_project_root() -> Path:
11
+ """Find the project root by looking for marker files.
12
+
13
+ Searches up from the package location for directories containing
14
+ .git, CLAUDE.md, or a templates/ directory.
15
+
16
+ Returns:
17
+ Path to the project root, or current working directory if not found.
18
+ """
19
+ # Start from the package directory
20
+ current = Path(__file__).parent.resolve()
21
+
22
+ # Walk up the directory tree
23
+ for _ in range(10): # Limit search depth
24
+ # Check for project root markers
25
+ if (current / '.git').exists() or (current / 'CLAUDE.md').exists():
26
+ return current
27
+ # Check if templates directory exists here
28
+ if (current / 'templates').is_dir():
29
+ return current
30
+ # Move up one level
31
+ parent = current.parent
32
+ if parent == current:
33
+ break
34
+ current = parent
35
+
36
+ # Fallback to current working directory
37
+ return Path.cwd()
38
+
39
+
40
+ # Default templates directory (relative to project root)
41
+ DEFAULT_TEMPLATES_DIR = _find_project_root() / 'templates'
42
+
43
+
44
+ def resolve_templates_dir(templates_dir: Optional[Path] = None) -> Path:
45
+ """Resolve the templates directory path.
46
+
47
+ Args:
48
+ templates_dir: Optional custom templates directory.
49
+
50
+ Returns:
51
+ Resolved Path to templates directory.
52
+ """
53
+ if templates_dir is not None:
54
+ return Path(templates_dir)
55
+ return DEFAULT_TEMPLATES_DIR
56
+
57
+
58
+ def list_templates(templates_dir: Optional[Path] = None) -> List[Dict[str, str]]:
59
+ """List all available templates.
60
+
61
+ Args:
62
+ templates_dir: Optional custom templates directory.
63
+
64
+ Returns:
65
+ List of dictionaries with template info (name, description, path).
66
+ """
67
+ templates_path = resolve_templates_dir(templates_dir)
68
+
69
+ if not templates_path.exists():
70
+ return []
71
+
72
+ templates = []
73
+ for item in templates_path.iterdir():
74
+ if item.is_dir():
75
+ manifest_path = item / 'manifest.xml'
76
+ template_info = {
77
+ 'name': item.name,
78
+ 'description': '',
79
+ 'path': str(item),
80
+ 'has_variables': False
81
+ }
82
+
83
+ # Try to read manifest for more info
84
+ if manifest_path.exists():
85
+ try:
86
+ tree = ET.parse(manifest_path)
87
+ root = tree.getroot()
88
+
89
+ # Get description if available
90
+ desc = root.find('description')
91
+ if desc is not None and desc.text:
92
+ template_info['description'] = desc.text
93
+
94
+ # Check for variables
95
+ features = root.find('features')
96
+ if features is not None:
97
+ for child in features:
98
+ if child.findall('variable'):
99
+ template_info['has_variables'] = True
100
+ break
101
+ except Exception:
102
+ pass
103
+
104
+ # Check if template.docx exists
105
+ if (item / 'template.docx').exists():
106
+ templates.append(template_info)
107
+
108
+ return templates
109
+
110
+
111
+ def load_template(
112
+ template_name: str,
113
+ templates_dir: Optional[Path] = None
114
+ ) -> Dict[str, Any]:
115
+ """Load a template by name.
116
+
117
+ Args:
118
+ template_name: Name of the template to load.
119
+ templates_dir: Optional custom templates directory.
120
+
121
+ Returns:
122
+ Dictionary containing template information and paths.
123
+
124
+ Raises:
125
+ FileNotFoundError: If template doesn't exist.
126
+ """
127
+ templates_path = resolve_templates_dir(templates_dir)
128
+ template_path = templates_path / template_name
129
+
130
+ if not template_path.exists():
131
+ raise FileNotFoundError(f"Template not found: {template_name}")
132
+
133
+ template_docx = template_path / 'template.docx'
134
+ if not template_docx.exists():
135
+ raise FileNotFoundError(f"Template DOCX not found: {template_docx}")
136
+
137
+ result = {
138
+ 'name': template_name,
139
+ 'path': template_path,
140
+ 'template_docx': template_docx,
141
+ 'fonts_dir': template_path / 'fonts' if (template_path / 'fonts').exists() else None,
142
+ 'variables': [],
143
+ 'styles': None,
144
+ 'has_cover_page': False,
145
+ 'has_textbox_variables': False
146
+ }
147
+
148
+ # Load manifest to check for cover page and features
149
+ manifest_path = template_path / 'manifest.xml'
150
+ if manifest_path.exists():
151
+ try:
152
+ tree = ET.parse(manifest_path)
153
+ root = tree.getroot()
154
+ features = root.find('features')
155
+ if features is not None:
156
+ # Check cover-page
157
+ cover_page = features.find('cover-page')
158
+ if cover_page is not None:
159
+ result['has_cover_page'] = cover_page.get('enabled', 'false').lower() == 'true'
160
+ # Check textbox
161
+ textbox = features.find('textbox')
162
+ if textbox is not None:
163
+ result['has_textbox_variables'] = textbox.get('enabled', 'false').lower() == 'true'
164
+ except Exception:
165
+ pass
166
+
167
+ # Load variables
168
+ variables_path = template_path / 'variables.xml'
169
+ if variables_path.exists():
170
+ try:
171
+ tree = ET.parse(variables_path)
172
+ root = tree.getroot()
173
+ for var in root.findall('variable'):
174
+ result['variables'].append({
175
+ 'name': var.get('name', ''),
176
+ 'syntax': var.get('syntax', 'both'),
177
+ 'location': var.findtext('location', ''),
178
+ 'original': var.findtext('original-content', ''),
179
+ 'default': var.findtext('default', '')
180
+ })
181
+ except Exception:
182
+ pass
183
+
184
+ # Load styles path
185
+ styles_path = template_path / 'styles.xml'
186
+ if styles_path.exists():
187
+ result['styles'] = styles_path
188
+
189
+ return result
190
+
191
+
192
+ def replace_variable(text: str, var_name: str, value: str) -> str:
193
+ """Replace a variable in text, supporting both syntaxes.
194
+
195
+ Replaces both <var_name> and {{var_name}} with the given value.
196
+
197
+ Args:
198
+ text: The text containing variables.
199
+ var_name: The variable name to replace.
200
+ value: The value to substitute.
201
+
202
+ Returns:
203
+ Text with variables replaced.
204
+ """
205
+ # Replace angle bracket syntax: <var_name>
206
+ text = text.replace(f'<{var_name}>', value)
207
+
208
+ # Replace double brace syntax: {{var_name}}
209
+ text = text.replace(f'{{{{{var_name}}}}}', value)
210
+
211
+ return text
212
+
213
+
214
+ def replace_all_variables(text: str, variables: Dict[str, str]) -> str:
215
+ """Replace all variables in text.
216
+
217
+ Args:
218
+ text: The text containing variables.
219
+ variables: Dictionary mapping variable names to values.
220
+
221
+ Returns:
222
+ Text with all variables replaced.
223
+ """
224
+ for var_name, value in variables.items():
225
+ text = replace_variable(text, var_name, value)
226
+ return text
227
+
228
+
229
+ def _run_has_special_elements(run) -> bool:
230
+ """Check if a run contains special elements that would be lost if text is set.
231
+
232
+ Setting run.text replaces the entire run content, which would lose
233
+ page breaks, drawings, and other special elements.
234
+
235
+ Args:
236
+ run: The Run object to check.
237
+
238
+ Returns:
239
+ True if the run contains special elements that should be preserved.
240
+ """
241
+ w_ns = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
242
+
243
+ # Check for page breaks
244
+ for br in run._element.iter(f'{w_ns}br'):
245
+ br_type = br.get(f'{w_ns}type')
246
+ if br_type == 'page':
247
+ return True
248
+
249
+ # Check for drawings (images, shapes)
250
+ drawing_ns = '{http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing}'
251
+ if run._element.find(f'.//{drawing_ns}drawing') is not None:
252
+ return True
253
+ if run._element.find(f'.//w:drawing', {'w': w_ns[1:-1]}) is not None:
254
+ return True
255
+
256
+ return False
257
+
258
+
259
+ def _safe_replace_run_text(run, variables: Dict[str, str]) -> None:
260
+ """Safely replace variables in a run's text without losing special elements.
261
+
262
+ Only modifies the run if:
263
+ 1. The run has text
264
+ 2. The text actually changes after replacement
265
+ 3. The run doesn't contain special elements (page breaks, etc.)
266
+
267
+ Args:
268
+ run: The Run object to modify.
269
+ variables: Dictionary mapping variable names to values.
270
+ """
271
+ if not run.text:
272
+ return
273
+
274
+ new_text = replace_all_variables(run.text, variables)
275
+
276
+ # Only modify if text actually changes
277
+ if new_text == run.text:
278
+ return
279
+
280
+ # Don't modify runs with special elements
281
+ if _run_has_special_elements(run):
282
+ return
283
+
284
+ run.text = new_text
285
+
286
+
287
+ def replace_placeholders_in_document(
288
+ doc: Document,
289
+ variables: Dict[str, str]
290
+ ) -> None:
291
+ """Replace variable placeholders throughout the document.
292
+
293
+ Supports both <variable> and {{variable}} syntax.
294
+
295
+ Note: This function is careful not to modify runs that contain special
296
+ elements like page breaks, as setting run.text would lose those elements.
297
+
298
+ Args:
299
+ doc: The Document to modify.
300
+ variables: Dictionary mapping variable names to values.
301
+ """
302
+ # Replace in body paragraphs
303
+ for para in doc.paragraphs:
304
+ for run in para.runs:
305
+ _safe_replace_run_text(run, variables)
306
+
307
+ # Replace in headers
308
+ for section in doc.sections:
309
+ for para in section.header.paragraphs:
310
+ for run in para.runs:
311
+ _safe_replace_run_text(run, variables)
312
+
313
+ # Replace in footers
314
+ for section in doc.sections:
315
+ for para in section.footer.paragraphs:
316
+ for run in para.runs:
317
+ _safe_replace_run_text(run, variables)
318
+
319
+ # Replace in tables
320
+ for table in doc.tables:
321
+ for row in table.rows:
322
+ for cell in row.cells:
323
+ for para in cell.paragraphs:
324
+ for run in para.runs:
325
+ _safe_replace_run_text(run, variables)
326
+
327
+
328
+ def replace_placeholders_in_header(doc: Document, document_name: str, document_title: str) -> None:
329
+ """Replace placeholder text in document headers.
330
+
331
+ Supports both <placeholder> and {{placeholder}} syntax.
332
+
333
+ Args:
334
+ doc: Document object.
335
+ document_name: Text to replace document name placeholder.
336
+ document_title: Text to replace document title placeholder.
337
+ """
338
+ for section in doc.sections:
339
+ header = section.header
340
+ for paragraph in header.paragraphs:
341
+ # Check for both syntax forms
342
+ has_placeholder = (
343
+ '<document name>' in paragraph.text or
344
+ '<document title>' in paragraph.text or
345
+ '{{document name}}' in paragraph.text or
346
+ '{{document_name}}' in paragraph.text or
347
+ '{{document title}}' in paragraph.text or
348
+ '{{document_title}}' in paragraph.text
349
+ )
350
+ if has_placeholder:
351
+ # Replace placeholders in paragraph text (both syntaxes)
352
+ text = paragraph.text
353
+ # Angle bracket syntax
354
+ text = text.replace('<document name>', document_name)
355
+ text = text.replace('<document title>', document_title)
356
+ # Double brace syntax (with space)
357
+ text = text.replace('{{document name}}', document_name)
358
+ text = text.replace('{{document title}}', document_title)
359
+ # Double brace syntax (with underscore)
360
+ text = text.replace('{{document_name}}', document_name)
361
+ text = text.replace('{{document_title}}', document_title)
362
+
363
+ # Clear existing runs and add new text
364
+ for run in paragraph.runs:
365
+ run.text = ''
366
+ if paragraph.runs:
367
+ paragraph.runs[0].text = text
368
+ else:
369
+ paragraph.add_run(text)
370
+
371
+
372
+ def apply_template(
373
+ output_path: Path,
374
+ template_path: Path,
375
+ document_name: Optional[str] = None,
376
+ document_title: Optional[str] = None
377
+ ) -> None:
378
+ """Apply template to generated DOCX file.
379
+
380
+ This function:
381
+ 1. Opens the generated DOCX file
382
+ 2. Replaces placeholders in headers
383
+ 3. Preserves footers from template
384
+
385
+ Args:
386
+ output_path: Path to the generated DOCX file.
387
+ template_path: Path to the template DOCX file.
388
+ document_name: Text for document name placeholder.
389
+ document_title: Text for document title placeholder.
390
+ """
391
+ if not template_path.exists():
392
+ print(f"Warning: Template not found at {template_path}, skipping template application")
393
+ return
394
+
395
+ # Open the generated document
396
+ doc = Document(output_path)
397
+ template_doc = Document(template_path)
398
+
399
+ # Get the first section from template (we'll apply this to all sections in generated doc)
400
+ if len(template_doc.sections) == 0:
401
+ print("Warning: Template has no sections, skipping template application")
402
+ return
403
+
404
+ template_section = template_doc.sections[0]
405
+
406
+ # Copy header and footer from template to all sections in generated document
407
+ for section in doc.sections:
408
+ # Copy header
409
+ section.header._element.clear()
410
+ for element in template_section.header._element:
411
+ section.header._element.append(element)
412
+
413
+ # Copy footer
414
+ section.footer._element.clear()
415
+ for element in template_section.footer._element:
416
+ section.footer._element.append(element)
417
+
418
+ # Replace placeholders in headers
419
+ if document_name or document_title:
420
+ replace_placeholders_in_header(
421
+ doc,
422
+ document_name or '',
423
+ document_title or ''
424
+ )
425
+
426
+ # Save the modified document
427
+ doc.save(output_path)