@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,420 @@
1
+ """Style extraction module for DOCX documents."""
2
+ from pathlib import Path
3
+ from typing import Dict, List, Optional, Any
4
+ from dataclasses import dataclass, field
5
+ from xml.etree import ElementTree as ET
6
+ from xml.dom import minidom
7
+ from docx import Document
8
+ from docx.shared import Pt, RGBColor
9
+ from docx.oxml.ns import qn
10
+
11
+
12
+ @dataclass
13
+ class StyleInfo:
14
+ """Information about a document style."""
15
+ name: str
16
+ font_name: Optional[str] = None
17
+ font_size: Optional[int] = None # In half-points (Word internal unit)
18
+ bold: bool = False
19
+ italic: bool = False
20
+ underline: bool = False
21
+ color: Optional[str] = None # Hex color without #
22
+ background_color: Optional[str] = None
23
+ spacing_before: Optional[int] = None # In twips
24
+ spacing_after: Optional[int] = None
25
+ line_spacing: Optional[float] = None
26
+ alignment: Optional[str] = None # left, center, right, justify
27
+ indent_left: Optional[int] = None
28
+ indent_right: Optional[int] = None
29
+ indent_first_line: Optional[int] = None
30
+ metadata: Dict[str, Any] = field(default_factory=dict)
31
+
32
+
33
+ @dataclass
34
+ class TableStyleInfo:
35
+ """Information about a table style."""
36
+ name: str
37
+ header_fill_color: Optional[str] = None
38
+ header_text_color: Optional[str] = None
39
+ header_bold: bool = True
40
+ row_band_color: Optional[str] = None # Alternating row color
41
+ border_color: Optional[str] = None
42
+ border_width: Optional[int] = None
43
+ cell_padding: Optional[int] = None
44
+
45
+
46
+ def extract_paragraph_style(style) -> StyleInfo:
47
+ """Extract style information from a paragraph style.
48
+
49
+ Args:
50
+ style: The docx style object.
51
+
52
+ Returns:
53
+ StyleInfo containing the extracted information.
54
+ """
55
+ info = StyleInfo(name=style.name)
56
+
57
+ # Get font information
58
+ font = style.font
59
+ if font:
60
+ if font.name:
61
+ info.font_name = font.name
62
+ if font.size:
63
+ info.font_size = font.size.pt * 2 # Convert to half-points
64
+ info.bold = font.bold or False
65
+ info.italic = font.italic or False
66
+ info.underline = font.underline or False
67
+ if font.color and font.color.rgb:
68
+ info.color = str(font.color.rgb)
69
+
70
+ # Get paragraph formatting
71
+ pf = style.paragraph_format
72
+ if pf:
73
+ if pf.space_before:
74
+ info.spacing_before = pf.space_before.twips
75
+ if pf.space_after:
76
+ info.spacing_after = pf.space_after.twips
77
+ if pf.line_spacing:
78
+ info.line_spacing = pf.line_spacing
79
+ if pf.alignment is not None:
80
+ alignment_map = {0: 'left', 1: 'center', 2: 'right', 3: 'justify'}
81
+ info.alignment = alignment_map.get(pf.alignment, 'left')
82
+ if pf.left_indent:
83
+ info.indent_left = pf.left_indent.twips
84
+ if pf.right_indent:
85
+ info.indent_right = pf.right_indent.twips
86
+ if pf.first_line_indent:
87
+ info.indent_first_line = pf.first_line_indent.twips
88
+
89
+ return info
90
+
91
+
92
+ def extract_styles(doc_path: Path) -> Dict[str, StyleInfo]:
93
+ """Extract all styles from a DOCX document.
94
+
95
+ Args:
96
+ doc_path: Path to the DOCX file.
97
+
98
+ Returns:
99
+ Dictionary mapping style names to StyleInfo objects.
100
+ """
101
+ doc = Document(doc_path)
102
+ styles = {}
103
+
104
+ # Extract paragraph styles
105
+ for style in doc.styles:
106
+ if style.type == 1: # Paragraph style
107
+ try:
108
+ info = extract_paragraph_style(style)
109
+ styles[style.name] = info
110
+ except Exception:
111
+ # Skip styles that can't be parsed
112
+ pass
113
+
114
+ return styles
115
+
116
+
117
+ def extract_table_styles(doc_path: Path) -> List[TableStyleInfo]:
118
+ """Extract table style information from a document.
119
+
120
+ Args:
121
+ doc_path: Path to the DOCX file.
122
+
123
+ Returns:
124
+ List of TableStyleInfo objects.
125
+ """
126
+ doc = Document(doc_path)
127
+ table_styles = []
128
+
129
+ for i, table in enumerate(doc.tables):
130
+ style_info = TableStyleInfo(name=f"Table_{i + 1}")
131
+
132
+ # Try to get header row styling
133
+ if table.rows:
134
+ first_row = table.rows[0]
135
+ for cell in first_row.cells:
136
+ # Check for shading (fill color)
137
+ tc = cell._tc
138
+ tcPr = tc.get_or_add_tcPr()
139
+ shd = tcPr.find(qn('w:shd'))
140
+ if shd is not None:
141
+ fill = shd.get(qn('w:fill'))
142
+ if fill and fill != 'auto':
143
+ style_info.header_fill_color = fill
144
+
145
+ # Check text formatting in header
146
+ for para in cell.paragraphs:
147
+ for run in para.runs:
148
+ if run.bold:
149
+ style_info.header_bold = True
150
+ if run.font.color and run.font.color.rgb:
151
+ style_info.header_text_color = str(run.font.color.rgb)
152
+ break # Only check first cell
153
+
154
+ table_styles.append(style_info)
155
+
156
+ return table_styles
157
+
158
+
159
+ def style_to_xml(style: StyleInfo) -> ET.Element:
160
+ """Convert a StyleInfo to an XML element.
161
+
162
+ Args:
163
+ style: The StyleInfo to convert.
164
+
165
+ Returns:
166
+ XML Element representing the style.
167
+ """
168
+ elem = ET.Element('style')
169
+ elem.set('name', style.name)
170
+
171
+ # Font element
172
+ if style.font_name or style.font_size:
173
+ font = ET.SubElement(elem, 'font')
174
+ if style.font_name:
175
+ font.set('name', style.font_name)
176
+ if style.font_size:
177
+ font.set('size', str(style.font_size))
178
+ if style.bold:
179
+ font.set('bold', 'true')
180
+ if style.italic:
181
+ font.set('italic', 'true')
182
+ if style.underline:
183
+ font.set('underline', 'true')
184
+
185
+ # Color
186
+ if style.color:
187
+ color = ET.SubElement(elem, 'color')
188
+ color.set('value', style.color)
189
+
190
+ # Background color
191
+ if style.background_color:
192
+ fill = ET.SubElement(elem, 'fill')
193
+ fill.set('color', style.background_color)
194
+
195
+ # Spacing
196
+ if style.spacing_before is not None or style.spacing_after is not None:
197
+ spacing = ET.SubElement(elem, 'spacing')
198
+ if style.spacing_before is not None:
199
+ spacing.set('before', str(style.spacing_before))
200
+ if style.spacing_after is not None:
201
+ spacing.set('after', str(style.spacing_after))
202
+ if style.line_spacing is not None:
203
+ spacing.set('line', str(style.line_spacing))
204
+
205
+ # Alignment
206
+ if style.alignment:
207
+ align = ET.SubElement(elem, 'alignment')
208
+ align.set('value', style.alignment)
209
+
210
+ # Indentation
211
+ if style.indent_left or style.indent_right or style.indent_first_line:
212
+ indent = ET.SubElement(elem, 'indent')
213
+ if style.indent_left:
214
+ indent.set('left', str(style.indent_left))
215
+ if style.indent_right:
216
+ indent.set('right', str(style.indent_right))
217
+ if style.indent_first_line:
218
+ indent.set('first-line', str(style.indent_first_line))
219
+
220
+ return elem
221
+
222
+
223
+ def table_style_to_xml(style: TableStyleInfo) -> ET.Element:
224
+ """Convert a TableStyleInfo to an XML element.
225
+
226
+ Args:
227
+ style: The TableStyleInfo to convert.
228
+
229
+ Returns:
230
+ XML Element representing the table style.
231
+ """
232
+ elem = ET.Element('table-style')
233
+ elem.set('name', style.name)
234
+
235
+ if style.header_fill_color:
236
+ header = ET.SubElement(elem, 'header')
237
+ header.set('fill', style.header_fill_color)
238
+ if style.header_text_color:
239
+ header.set('text-color', style.header_text_color)
240
+ header.set('bold', 'true' if style.header_bold else 'false')
241
+
242
+ if style.row_band_color:
243
+ band = ET.SubElement(elem, 'row-banding')
244
+ band.set('color', style.row_band_color)
245
+
246
+ if style.border_color or style.border_width:
247
+ border = ET.SubElement(elem, 'border')
248
+ if style.border_color:
249
+ border.set('color', style.border_color)
250
+ if style.border_width:
251
+ border.set('width', str(style.border_width))
252
+
253
+ return elem
254
+
255
+
256
+ def save_styles(
257
+ styles: Dict[str, StyleInfo],
258
+ table_styles: List[TableStyleInfo],
259
+ output_path: Path
260
+ ) -> None:
261
+ """Save extracted styles to an XML file.
262
+
263
+ Args:
264
+ styles: Dictionary of paragraph styles.
265
+ table_styles: List of table styles.
266
+ output_path: Path to save the styles XML.
267
+ """
268
+ root = ET.Element('styles')
269
+ root.set('version', '1.0')
270
+
271
+ # Add paragraph styles
272
+ para_styles = ET.SubElement(root, 'paragraph-styles')
273
+ for style in styles.values():
274
+ para_styles.append(style_to_xml(style))
275
+
276
+ # Add table styles
277
+ tbl_styles = ET.SubElement(root, 'table-styles')
278
+ for style in table_styles:
279
+ tbl_styles.append(table_style_to_xml(style))
280
+
281
+ # Pretty print and save
282
+ rough_string = ET.tostring(root, encoding='unicode')
283
+ reparsed = minidom.parseString(rough_string)
284
+ formatted = reparsed.toprettyxml(indent=" ")
285
+
286
+ output_path.parent.mkdir(parents=True, exist_ok=True)
287
+ output_path.write_text(formatted, encoding='utf-8')
288
+
289
+
290
+ def load_styles(styles_path: Path) -> Dict[str, StyleInfo]:
291
+ """Load styles from an XML file.
292
+
293
+ Args:
294
+ styles_path: Path to the styles XML file.
295
+
296
+ Returns:
297
+ Dictionary mapping style names to StyleInfo objects.
298
+ """
299
+ if not styles_path.exists():
300
+ raise FileNotFoundError(f"Styles file not found: {styles_path}")
301
+
302
+ tree = ET.parse(styles_path)
303
+ root = tree.getroot()
304
+
305
+ styles = {}
306
+
307
+ para_styles = root.find('paragraph-styles')
308
+ if para_styles is not None:
309
+ for style_elem in para_styles.findall('style'):
310
+ name = style_elem.get('name', '')
311
+ info = StyleInfo(name=name)
312
+
313
+ # Parse font
314
+ font = style_elem.find('font')
315
+ if font is not None:
316
+ info.font_name = font.get('name')
317
+ size = font.get('size')
318
+ if size:
319
+ info.font_size = int(size)
320
+ info.bold = font.get('bold') == 'true'
321
+ info.italic = font.get('italic') == 'true'
322
+ info.underline = font.get('underline') == 'true'
323
+
324
+ # Parse color
325
+ color = style_elem.find('color')
326
+ if color is not None:
327
+ info.color = color.get('value')
328
+
329
+ # Parse fill
330
+ fill = style_elem.find('fill')
331
+ if fill is not None:
332
+ info.background_color = fill.get('color')
333
+
334
+ # Parse spacing
335
+ spacing = style_elem.find('spacing')
336
+ if spacing is not None:
337
+ before = spacing.get('before')
338
+ after = spacing.get('after')
339
+ line = spacing.get('line')
340
+ if before:
341
+ info.spacing_before = int(before)
342
+ if after:
343
+ info.spacing_after = int(after)
344
+ if line:
345
+ info.line_spacing = float(line)
346
+
347
+ # Parse alignment
348
+ align = style_elem.find('alignment')
349
+ if align is not None:
350
+ info.alignment = align.get('value')
351
+
352
+ # Parse indent
353
+ indent = style_elem.find('indent')
354
+ if indent is not None:
355
+ left = indent.get('left')
356
+ right = indent.get('right')
357
+ first = indent.get('first-line')
358
+ if left:
359
+ info.indent_left = int(left)
360
+ if right:
361
+ info.indent_right = int(right)
362
+ if first:
363
+ info.indent_first_line = int(first)
364
+
365
+ styles[name] = info
366
+
367
+ return styles
368
+
369
+
370
+ def apply_styles(doc: Document, styles: Dict[str, StyleInfo]) -> None:
371
+ """Apply loaded styles to a document.
372
+
373
+ This function modifies the document in place to apply the given styles.
374
+
375
+ Args:
376
+ doc: The Document to modify.
377
+ styles: Dictionary of styles to apply.
378
+ """
379
+ # This is a placeholder for style application logic
380
+ # Full implementation would require modifying the document's style definitions
381
+ # which is complex with python-docx
382
+ pass
383
+
384
+
385
+ def get_styles_path(document_path: Path) -> Path:
386
+ """Get the styles file path for a document.
387
+
388
+ Args:
389
+ document_path: Path to the Markdown or DOCX file.
390
+
391
+ Returns:
392
+ Path to the corresponding _styles.xml file.
393
+ """
394
+ return document_path.parent / f"{document_path.stem}_styles.xml"
395
+
396
+
397
+ def save_styles_to_both_locations(
398
+ styles: Dict[str, StyleInfo],
399
+ table_styles: List[TableStyleInfo],
400
+ source_path: Path,
401
+ output_path: Path
402
+ ) -> None:
403
+ """Save extracted styles to both source and output locations.
404
+
405
+ Args:
406
+ styles: Dictionary of paragraph styles.
407
+ table_styles: List of table styles.
408
+ source_path: Path to the source file (DOCX).
409
+ output_path: Path to the output file (MD).
410
+ """
411
+ # Get styles paths for both locations
412
+ source_styles = get_styles_path(source_path)
413
+ output_styles = get_styles_path(output_path)
414
+
415
+ # Save to source location
416
+ save_styles(styles, table_styles, source_styles)
417
+
418
+ # Save to output location if different
419
+ if source_styles != output_styles:
420
+ save_styles(styles, table_styles, output_styles)
@@ -0,0 +1,294 @@
1
+ """SVG embedding support for Word documents.
2
+
3
+ This module provides functionality to embed SVG images directly in DOCX files.
4
+ Requires python-docx-ng for SVG support (standard python-docx does not support SVG).
5
+
6
+ Usage:
7
+ from document_converter.svg_embedder import (
8
+ is_svg_embedding_available,
9
+ embed_svg_in_docx,
10
+ convert_svg_to_png_fallback
11
+ )
12
+
13
+ if is_svg_embedding_available():
14
+ embed_svg_in_docx(doc, svg_path, width, height)
15
+ else:
16
+ # Fall back to PNG
17
+ png_path = convert_svg_to_png_fallback(svg_path)
18
+ doc.add_picture(str(png_path), width=width)
19
+ """
20
+ import subprocess
21
+ from pathlib import Path
22
+ from typing import Optional, Tuple
23
+ import warnings
24
+
25
+
26
+ # Cache the availability check result
27
+ _svg_embedding_available: Optional[bool] = None
28
+
29
+
30
+ def is_svg_embedding_available() -> bool:
31
+ """Check if SVG embedding is available.
32
+
33
+ SVG embedding requires python-docx-ng which extends python-docx
34
+ with SVG support.
35
+
36
+ Returns:
37
+ True if python-docx-ng is installed and SVG embedding works.
38
+ """
39
+ global _svg_embedding_available
40
+
41
+ if _svg_embedding_available is not None:
42
+ return _svg_embedding_available
43
+
44
+ try:
45
+ from docx import Document
46
+ from docx.image.exceptions import UnrecognizedImageError
47
+
48
+ # Create a minimal test SVG
49
+ test_svg = b'''<?xml version="1.0"?>
50
+ <svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">
51
+ <rect width="1" height="1"/>
52
+ </svg>'''
53
+
54
+ import tempfile
55
+ with tempfile.NamedTemporaryFile(suffix='.svg', delete=False) as f:
56
+ f.write(test_svg)
57
+ test_path = f.name
58
+
59
+ try:
60
+ doc = Document()
61
+ doc.add_picture(test_path)
62
+ _svg_embedding_available = True
63
+ except UnrecognizedImageError:
64
+ _svg_embedding_available = False
65
+ finally:
66
+ Path(test_path).unlink(missing_ok=True)
67
+
68
+ except ImportError:
69
+ _svg_embedding_available = False
70
+
71
+ return _svg_embedding_available
72
+
73
+
74
+ def get_svg_dimensions(svg_path: Path) -> Tuple[Optional[int], Optional[int]]:
75
+ """Extract dimensions from an SVG file.
76
+
77
+ Parses the SVG to get width and height attributes or viewBox dimensions.
78
+
79
+ Args:
80
+ svg_path: Path to the SVG file.
81
+
82
+ Returns:
83
+ Tuple of (width, height) in pixels, or (None, None) if not determinable.
84
+ """
85
+ try:
86
+ import xml.etree.ElementTree as ET
87
+
88
+ tree = ET.parse(svg_path)
89
+ root = tree.getroot()
90
+
91
+ # Try to get width/height attributes
92
+ width_str = root.attrib.get('width', '')
93
+ height_str = root.attrib.get('height', '')
94
+
95
+ def parse_dimension(dim_str: str) -> Optional[int]:
96
+ """Parse a dimension string to pixels."""
97
+ if not dim_str:
98
+ return None
99
+ # Remove units and convert to int
100
+ dim_str = dim_str.strip()
101
+ for unit in ('px', 'pt', 'em', 'rem', '%'):
102
+ dim_str = dim_str.replace(unit, '')
103
+ try:
104
+ return int(float(dim_str))
105
+ except ValueError:
106
+ return None
107
+
108
+ width = parse_dimension(width_str)
109
+ height = parse_dimension(height_str)
110
+
111
+ # If dimensions not found, try viewBox
112
+ if width is None or height is None:
113
+ viewbox = root.attrib.get('viewBox', '')
114
+ if viewbox:
115
+ parts = viewbox.split()
116
+ if len(parts) >= 4:
117
+ try:
118
+ width = int(float(parts[2]))
119
+ height = int(float(parts[3]))
120
+ except ValueError:
121
+ pass
122
+
123
+ return width, height
124
+
125
+ except Exception:
126
+ return None, None
127
+
128
+
129
+ def convert_svg_to_png(svg_path: Path, output_path: Optional[Path] = None) -> Path:
130
+ """Convert an SVG file to PNG using available tools.
131
+
132
+ Tries multiple conversion methods in order:
133
+ 1. Mermaid CLI (mmdc) - if available
134
+ 2. cairosvg - if installed
135
+ 3. Inkscape - if installed
136
+
137
+ Args:
138
+ svg_path: Path to the input SVG file.
139
+ output_path: Optional output path. If None, uses same name with .png extension.
140
+
141
+ Returns:
142
+ Path to the generated PNG file.
143
+
144
+ Raises:
145
+ RuntimeError: If no conversion tool is available or conversion fails.
146
+ """
147
+ if output_path is None:
148
+ output_path = svg_path.with_suffix('.png')
149
+
150
+ # Try cairosvg first (Python library, most reliable)
151
+ try:
152
+ import cairosvg
153
+ cairosvg.svg2png(url=str(svg_path), write_to=str(output_path))
154
+ if output_path.exists():
155
+ return output_path
156
+ except ImportError:
157
+ pass
158
+ except Exception as e:
159
+ warnings.warn(f"cairosvg conversion failed: {e}")
160
+
161
+ # Try Inkscape
162
+ try:
163
+ result = subprocess.run(
164
+ ['inkscape', '--export-type=png', '--export-filename=' + str(output_path), str(svg_path)],
165
+ capture_output=True,
166
+ timeout=30
167
+ )
168
+ if result.returncode == 0 and output_path.exists():
169
+ return output_path
170
+ except (FileNotFoundError, subprocess.TimeoutExpired):
171
+ pass
172
+ except Exception as e:
173
+ warnings.warn(f"Inkscape conversion failed: {e}")
174
+
175
+ # Try rsvg-convert (part of librsvg)
176
+ try:
177
+ result = subprocess.run(
178
+ ['rsvg-convert', '-o', str(output_path), str(svg_path)],
179
+ capture_output=True,
180
+ timeout=30
181
+ )
182
+ if result.returncode == 0 and output_path.exists():
183
+ return output_path
184
+ except (FileNotFoundError, subprocess.TimeoutExpired):
185
+ pass
186
+ except Exception as e:
187
+ warnings.warn(f"rsvg-convert conversion failed: {e}")
188
+
189
+ raise RuntimeError(
190
+ f"Failed to convert SVG to PNG. No conversion tool available. "
191
+ "Install one of: cairosvg (pip install cairosvg), Inkscape, or librsvg."
192
+ )
193
+
194
+
195
+ def embed_svg_images_in_docx(
196
+ docx_path: Path,
197
+ svg_paths: list[Path],
198
+ fallback_to_png: bool = True
199
+ ) -> dict:
200
+ """Replace PNG placeholders with SVG images in a DOCX file.
201
+
202
+ This is a post-processing step that can replace PNG images with their
203
+ SVG equivalents after the initial DOCX generation.
204
+
205
+ Args:
206
+ docx_path: Path to the DOCX file to modify.
207
+ svg_paths: List of SVG file paths to embed.
208
+ fallback_to_png: If True and SVG embedding unavailable, keep PNGs.
209
+
210
+ Returns:
211
+ Dictionary with 'embedded' count and any 'warnings'.
212
+ """
213
+ result = {
214
+ 'embedded': 0,
215
+ 'warnings': []
216
+ }
217
+
218
+ if not is_svg_embedding_available():
219
+ if fallback_to_png:
220
+ result['warnings'].append(
221
+ "SVG embedding not available (requires python-docx-ng). "
222
+ "Using PNG images instead."
223
+ )
224
+ return result
225
+ else:
226
+ raise RuntimeError(
227
+ "SVG embedding requires python-docx-ng. "
228
+ "Install with: pip install python-docx-ng"
229
+ )
230
+
231
+ # SVG embedding is available - this would be used for post-processing
232
+ # For now, we handle SVG at render time in the converters
233
+ result['embedded'] = len(svg_paths)
234
+ return result
235
+
236
+
237
+ def check_svg_embedding_requirements() -> dict:
238
+ """Check all requirements for SVG embedding.
239
+
240
+ Returns:
241
+ Dictionary with status information about SVG embedding capabilities.
242
+ """
243
+ status = {
244
+ 'svg_embedding_available': is_svg_embedding_available(),
245
+ 'docx_library': 'unknown',
246
+ 'svg_to_png_available': False,
247
+ 'svg_to_png_tool': None,
248
+ 'recommendations': []
249
+ }
250
+
251
+ # Check which docx library is installed
252
+ try:
253
+ import docx
254
+ # Check if it's python-docx-ng by testing SVG support
255
+ if is_svg_embedding_available():
256
+ status['docx_library'] = 'python-docx-ng'
257
+ else:
258
+ status['docx_library'] = 'python-docx'
259
+ status['recommendations'].append(
260
+ "For SVG embedding, install python-docx-ng: pip install python-docx-ng"
261
+ )
262
+ except ImportError:
263
+ status['docx_library'] = 'not installed'
264
+ status['recommendations'].append(
265
+ "Install python-docx: pip install python-docx"
266
+ )
267
+
268
+ # Check SVG to PNG conversion tools
269
+ try:
270
+ import cairosvg
271
+ status['svg_to_png_available'] = True
272
+ status['svg_to_png_tool'] = 'cairosvg'
273
+ except ImportError:
274
+ # Check for command-line tools
275
+ for tool in ['inkscape', 'rsvg-convert']:
276
+ try:
277
+ result = subprocess.run(
278
+ [tool, '--version'],
279
+ capture_output=True,
280
+ timeout=5
281
+ )
282
+ if result.returncode == 0:
283
+ status['svg_to_png_available'] = True
284
+ status['svg_to_png_tool'] = tool
285
+ break
286
+ except (FileNotFoundError, subprocess.TimeoutExpired):
287
+ continue
288
+
289
+ if not status['svg_to_png_available']:
290
+ status['recommendations'].append(
291
+ "For SVG to PNG fallback, install cairosvg: pip install cairosvg"
292
+ )
293
+
294
+ return status