@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,448 @@
1
+ """Cover page generator for DOCX documents."""
2
+ import re
3
+ from pathlib import Path
4
+ from typing import List, Optional
5
+ from copy import deepcopy
6
+ from docx import Document
7
+ from docx.shared import Pt, Inches
8
+ from docx.enum.text import WD_ALIGN_PARAGRAPH
9
+ from docx.oxml.ns import qn
10
+ from docx.oxml import OxmlElement
11
+ from lxml import etree
12
+
13
+
14
+ def get_min_heading_level(markdown_content: str) -> int:
15
+ """Get the minimum heading level used in the markdown content.
16
+
17
+ Args:
18
+ markdown_content: The markdown content to parse.
19
+
20
+ Returns:
21
+ Minimum heading level (1-6), or 0 if no headings found.
22
+ """
23
+ heading_pattern = re.compile(r'^(#{1,6})\s+.+$', re.MULTILINE)
24
+ matches = heading_pattern.findall(markdown_content)
25
+ if not matches:
26
+ return 0
27
+ return min(len(h) for h in matches)
28
+
29
+
30
+ def normalize_heading_levels(markdown_content: str) -> str:
31
+ """Normalize heading levels so that the minimum level becomes H1.
32
+
33
+ If markdown only contains H2+ headings (no H1), this promotes all headings
34
+ so the minimum level becomes H1. For example:
35
+ - If min is H2: H2→H1, H3→H2, H4→H3, etc.
36
+ - If min is H3: H3→H1, H4→H2, H5→H3, etc.
37
+
38
+ Args:
39
+ markdown_content: The markdown content to modify.
40
+
41
+ Returns:
42
+ Modified markdown with normalized heading levels.
43
+ """
44
+ min_level = get_min_heading_level(markdown_content)
45
+
46
+ # If no headings or already has H1, no normalization needed
47
+ if min_level <= 1:
48
+ return markdown_content
49
+
50
+ # Calculate how many levels to promote
51
+ levels_to_promote = min_level - 1
52
+
53
+ lines = markdown_content.split('\n')
54
+ result = []
55
+
56
+ for line in lines:
57
+ match = re.match(r'^(#{1,6})\s+(.+)$', line)
58
+ if match:
59
+ hashes = match.group(1)
60
+ text = match.group(2)
61
+ current_level = len(hashes)
62
+ new_level = current_level - levels_to_promote
63
+ # Ensure we don't go below H1
64
+ new_level = max(1, new_level)
65
+ line = '#' * new_level + ' ' + text
66
+ result.append(line)
67
+
68
+ return '\n'.join(result)
69
+
70
+
71
+ def count_h1_headings(markdown_content: str) -> int:
72
+ """Count the number of H1 headings in markdown content.
73
+
74
+ Args:
75
+ markdown_content: The markdown content to parse.
76
+
77
+ Returns:
78
+ Number of H1 headings found.
79
+ """
80
+ h1_pattern = re.compile(r'^#\s+.+$', re.MULTILINE)
81
+ return len(h1_pattern.findall(markdown_content))
82
+
83
+
84
+ def should_create_cover_page(markdown_content: str) -> bool:
85
+ """Determine if a cover page should be created.
86
+
87
+ A cover page is only created when there is exactly one H1 heading.
88
+
89
+ Args:
90
+ markdown_content: The markdown content to parse.
91
+
92
+ Returns:
93
+ True if cover page should be created, False otherwise.
94
+ """
95
+ return count_h1_headings(markdown_content) == 1
96
+
97
+
98
+ def demote_headings(markdown_content: str) -> str:
99
+ """Demote heading levels appropriately.
100
+
101
+ The original H1 line is removed (it goes to cover page).
102
+ Content under H1 (before first H2) is kept.
103
+ - H3/H4/etc before first H2 → H1 (promoted to top level)
104
+ - H2 → H1
105
+ - H3 after first H2 → H2
106
+ - etc.
107
+
108
+ Args:
109
+ markdown_content: The markdown content to modify.
110
+
111
+ Returns:
112
+ Modified markdown with adjusted headings.
113
+ """
114
+ lines = markdown_content.split('\n')
115
+ result = []
116
+ h1_found = False
117
+ first_h2_found = False
118
+
119
+ for line in lines:
120
+ # Skip the H1 line only (it goes to cover page)
121
+ if re.match(r'^#\s+[^#]', line) and not h1_found:
122
+ h1_found = True
123
+ continue
124
+
125
+ # Check if this is the first H2
126
+ if re.match(r'^##\s+[^#]', line) and not first_h2_found:
127
+ first_h2_found = True
128
+
129
+ # Handle headings based on position
130
+ if not first_h2_found:
131
+ # Before first H2: promote H3+ to H1
132
+ if re.match(r'^###+\s+', line):
133
+ line = re.sub(r'^###+\s+', '# ', line)
134
+ else:
135
+ # After first H2: demote normally (## -> #, ### -> ##, etc.)
136
+ if re.match(r'^######\s+', line):
137
+ line = re.sub(r'^######\s+', '##### ', line)
138
+ elif re.match(r'^#####\s+', line):
139
+ line = re.sub(r'^#####\s+', '#### ', line)
140
+ elif re.match(r'^####\s+', line):
141
+ line = re.sub(r'^####\s+', '### ', line)
142
+ elif re.match(r'^###\s+', line):
143
+ line = re.sub(r'^###\s+', '## ', line)
144
+ elif re.match(r'^##\s+', line):
145
+ line = re.sub(r'^##\s+', '# ', line)
146
+
147
+ result.append(line)
148
+
149
+ return '\n'.join(result)
150
+
151
+
152
+ def extract_title_and_description(markdown_content: str) -> tuple[str, str, bool]:
153
+ """Extract the H1 title and description from markdown content.
154
+
155
+ The description is any content between the H1 and the first H2.
156
+ Only extracts if there is exactly one H1 heading.
157
+
158
+ Args:
159
+ markdown_content: The markdown content to parse.
160
+
161
+ Returns:
162
+ Tuple of (title, description, should_create_cover).
163
+ Empty strings and False if cover page should not be created.
164
+ """
165
+ # Only create cover page if exactly one H1
166
+ if not should_create_cover_page(markdown_content):
167
+ return '', '', False
168
+ # Find H1 title (# Title)
169
+ h1_match = re.search(r'^#\s+(.+?)$', markdown_content, re.MULTILINE)
170
+ if not h1_match:
171
+ return '', '', False
172
+
173
+ title = h1_match.group(1).strip()
174
+
175
+ # Find content between H1 and first H2
176
+ h1_end = h1_match.end()
177
+ h2_match = re.search(r'^##\s+', markdown_content[h1_end:], re.MULTILINE)
178
+
179
+ if h2_match:
180
+ description_text = markdown_content[h1_end:h1_end + h2_match.start()]
181
+ else:
182
+ description_text = markdown_content[h1_end:]
183
+
184
+ # Clean up description - remove markdown formatting, keep text
185
+ description = description_text.strip()
186
+ # Remove ** bold markers but keep the text
187
+ description = re.sub(r'\*\*(.+?)\*\*', r'\1', description)
188
+ # Remove heading markers (### Header -> Header)
189
+ description = re.sub(r'^#{1,6}\s+', '', description, flags=re.MULTILINE)
190
+ # Remove bullet point markers (* item -> item, - item -> item)
191
+ description = re.sub(r'^\s*[\*\-]\s+', '', description, flags=re.MULTILINE)
192
+ # Remove horizontal rules
193
+ description = re.sub(r'^---+$', '', description, flags=re.MULTILINE)
194
+ # Clean up multiple blank lines
195
+ description = re.sub(r'\n{3,}', '\n\n', description)
196
+ description = description.strip()
197
+
198
+ return title, description, True
199
+
200
+
201
+ def create_page_break_paragraph():
202
+ """Create a paragraph with a page break.
203
+
204
+ Returns:
205
+ A paragraph element containing a page break.
206
+ """
207
+ paragraph = OxmlElement('w:p')
208
+ run = OxmlElement('w:r')
209
+ br = OxmlElement('w:br')
210
+ br.set(qn('w:type'), 'page')
211
+ run.append(br)
212
+ paragraph.append(run)
213
+ return paragraph
214
+
215
+
216
+ def add_cover_page(
217
+ docx_path: Path,
218
+ title: str,
219
+ description: str = ""
220
+ ) -> None:
221
+ """Add a cover page to the beginning of a DOCX document.
222
+
223
+ The cover page contains:
224
+ - Centered H1 title
225
+ - Description text below the title
226
+ - Page break after the cover page
227
+
228
+ Args:
229
+ docx_path: Path to the DOCX file.
230
+ title: The main title for the cover page.
231
+ description: Optional description text below the title.
232
+ """
233
+ if not title:
234
+ return
235
+
236
+ doc = Document(docx_path)
237
+ body = doc.element.body
238
+
239
+ # Find the first element
240
+ first_element = body[0] if len(body) > 0 else None
241
+
242
+ # Create cover page elements (in reverse order for insertion)
243
+ elements_to_insert = []
244
+
245
+ # Page break after cover page
246
+ page_break = create_page_break_paragraph()
247
+ elements_to_insert.append(page_break)
248
+
249
+ # Description paragraphs (if any)
250
+ if description:
251
+ for line in reversed(description.split('\n')):
252
+ line = line.strip()
253
+ if line:
254
+ desc_para = OxmlElement('w:p')
255
+
256
+ # Paragraph properties - center align with spacing
257
+ pPr = OxmlElement('w:pPr')
258
+ jc = OxmlElement('w:jc')
259
+ jc.set(qn('w:val'), 'center')
260
+ pPr.append(jc)
261
+
262
+ spacing = OxmlElement('w:spacing')
263
+ spacing.set(qn('w:after'), '120') # 6pt after
264
+ pPr.append(spacing)
265
+
266
+ desc_para.append(pPr)
267
+
268
+ # Run with text
269
+ run = OxmlElement('w:r')
270
+ rPr = OxmlElement('w:rPr')
271
+ sz = OxmlElement('w:sz')
272
+ sz.set(qn('w:val'), '24') # 12pt
273
+ rPr.append(sz)
274
+ run.append(rPr)
275
+
276
+ text_elem = OxmlElement('w:t')
277
+ text_elem.set(qn('xml:space'), 'preserve')
278
+ text_elem.text = line
279
+ run.append(text_elem)
280
+
281
+ desc_para.append(run)
282
+ elements_to_insert.append(desc_para)
283
+
284
+ # Spacer before description
285
+ spacer = OxmlElement('w:p')
286
+ spacer_pPr = OxmlElement('w:pPr')
287
+ spacer_spacing = OxmlElement('w:spacing')
288
+ spacer_spacing.set(qn('w:after'), '480') # 24pt after
289
+ spacer_pPr.append(spacer_spacing)
290
+ spacer.append(spacer_pPr)
291
+ elements_to_insert.append(spacer)
292
+
293
+ # Title paragraph - centered H1 style
294
+ title_para = OxmlElement('w:p')
295
+
296
+ # Paragraph properties
297
+ pPr = OxmlElement('w:pPr')
298
+
299
+ # Center alignment
300
+ jc = OxmlElement('w:jc')
301
+ jc.set(qn('w:val'), 'center')
302
+ pPr.append(jc)
303
+
304
+ # Spacing before (to push title down on page)
305
+ spacing = OxmlElement('w:spacing')
306
+ spacing.set(qn('w:before'), '4800') # ~2.5 inches from top
307
+ spacing.set(qn('w:after'), '240') # 12pt after
308
+ pPr.append(spacing)
309
+
310
+ title_para.append(pPr)
311
+
312
+ # Run with title text
313
+ run = OxmlElement('w:r')
314
+ rPr = OxmlElement('w:rPr')
315
+
316
+ # Bold
317
+ bold = OxmlElement('w:b')
318
+ rPr.append(bold)
319
+
320
+ # Font size - 36pt for cover title
321
+ sz = OxmlElement('w:sz')
322
+ sz.set(qn('w:val'), '72') # 36pt (half-points)
323
+ rPr.append(sz)
324
+
325
+ # Color - dark blue
326
+ color = OxmlElement('w:color')
327
+ color.set(qn('w:val'), '2F5496')
328
+ rPr.append(color)
329
+
330
+ run.append(rPr)
331
+
332
+ text_elem = OxmlElement('w:t')
333
+ text_elem.text = title
334
+ run.append(text_elem)
335
+
336
+ title_para.append(run)
337
+ elements_to_insert.append(title_para)
338
+
339
+ # Insert all elements at the beginning
340
+ for elem in elements_to_insert:
341
+ if first_element is not None:
342
+ first_element.addprevious(elem)
343
+ else:
344
+ body.append(elem)
345
+ first_element = elem
346
+
347
+ # Remove the original H1 from the document body (it's now on cover page)
348
+ # Find and remove the first Heading 1 paragraph
349
+ for para in doc.paragraphs:
350
+ if para.style and para.style.name == 'Heading 1':
351
+ # Check if this is our title
352
+ if para.text.strip() == title:
353
+ p_element = para._element
354
+ p_element.getparent().remove(p_element)
355
+ break
356
+
357
+ doc.save(docx_path)
358
+
359
+
360
+ def copy_template_cover_page(
361
+ output_path: Path,
362
+ template_path: Path
363
+ ) -> bool:
364
+ """Copy the cover page from a template to the output document.
365
+
366
+ This copies all elements from the template up to and including the first
367
+ page break, preserving textboxes, drawings, and other complex elements.
368
+
369
+ If the template has no page break (single-page cover template), all template
370
+ elements are copied as the cover page and a page break is added after.
371
+
372
+ Args:
373
+ output_path: Path to the output DOCX file.
374
+ template_path: Path to the template DOCX file.
375
+
376
+ Returns:
377
+ True if cover page was copied, False if template has no content.
378
+ """
379
+ template_doc = Document(template_path)
380
+ output_doc = Document(output_path)
381
+
382
+ template_body = template_doc.element.body
383
+ output_body = output_doc.element.body
384
+
385
+ w_ns = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
386
+
387
+ # Find all elements up to and including the first page break
388
+ cover_elements = []
389
+ found_page_break = False
390
+
391
+ for elem in template_body:
392
+ # Deep copy the element
393
+ elem_copy = deepcopy(elem)
394
+ cover_elements.append(elem_copy)
395
+
396
+ # Check if this element contains a page break
397
+ for br in elem.iter(f'{w_ns}br'):
398
+ if br.get(qn('w:type')) == 'page':
399
+ found_page_break = True
400
+ break
401
+
402
+ if found_page_break:
403
+ break
404
+
405
+ if not cover_elements:
406
+ return False
407
+
408
+ # Get the first element in output to insert before
409
+ first_output = output_body[0] if len(output_body) > 0 else None
410
+
411
+ # Insert cover page elements at the beginning of output document
412
+ for elem in reversed(cover_elements):
413
+ if first_output is not None:
414
+ first_output.addprevious(elem)
415
+ else:
416
+ output_body.append(elem)
417
+ first_output = elem
418
+
419
+ # If template had no page break, we need to add one after the cover page
420
+ # This ensures the content starts on a new page after the cover
421
+ if not found_page_break:
422
+ # Create a page break paragraph
423
+ page_break_para = create_page_break_paragraph()
424
+ # Insert after the last cover element (which is now at the beginning)
425
+ # cover_elements[0] after reversal is at the end, cover_elements[-1] is at start
426
+ # The first_output now points to the first cover element
427
+ # We need to insert the page break after the last cover element
428
+ last_cover_in_output = cover_elements[-1] # This was inserted first, so it's last
429
+ # Actually, after insertion, the order is: cover_elements[0], cover_elements[1], ... , cover_elements[-1]
430
+ # first_output now points to cover_elements[0]
431
+ # We need to find the last cover element and insert page break after it
432
+
433
+ # Find where to insert the page break (after all cover elements, before content)
434
+ # The safest way is to find the first non-cover element
435
+ content_start = None
436
+ for i, child in enumerate(output_body):
437
+ # Skip cover elements
438
+ if i >= len(cover_elements):
439
+ content_start = child
440
+ break
441
+
442
+ if content_start is not None:
443
+ content_start.addprevious(page_break_para)
444
+ else:
445
+ output_body.append(page_break_para)
446
+
447
+ output_doc.save(output_path)
448
+ return True # Always return True if we copied something