@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,356 @@
1
+ """Code block renderer - converts code to syntax-highlighted PNG images using Pygments."""
2
+ import platform
3
+ import re
4
+ from dataclasses import dataclass, field
5
+ from pathlib import Path
6
+ from typing import List, Optional, Tuple, Union
7
+
8
+ from pygments import highlight
9
+ from pygments.lexers import get_lexer_by_name, guess_lexer, TextLexer
10
+ from pygments.formatters import ImageFormatter
11
+ from pygments.styles import get_all_styles, get_style_by_name
12
+ from pygments.util import ClassNotFound
13
+ from PIL import Image, ImageFont
14
+
15
+
16
+ # Platform-specific monospace font preferences
17
+ MONOSPACE_FONTS_BY_PLATFORM = {
18
+ "darwin": ["Menlo", "Monaco", "SF Mono", "Courier New", "Courier"],
19
+ "linux": ["DejaVu Sans Mono", "Liberation Mono", "Ubuntu Mono", "Courier New", "Courier"],
20
+ "windows": ["Consolas", "Courier New", "Lucida Console", "Courier"],
21
+ }
22
+
23
+ # Fallback fonts for any platform
24
+ FALLBACK_FONTS = ["Courier New", "Courier", "monospace"]
25
+
26
+
27
+ def get_default_monospace_font() -> str:
28
+ """Get the default monospace font for the current platform.
29
+
30
+ Returns:
31
+ Font name that should be available on the current platform.
32
+ """
33
+ system = platform.system().lower()
34
+
35
+ # Get platform-specific fonts
36
+ fonts = MONOSPACE_FONTS_BY_PLATFORM.get(system, FALLBACK_FONTS)
37
+
38
+ # Try to find an available font
39
+ for font_name in fonts:
40
+ if _is_font_available(font_name):
41
+ return font_name
42
+
43
+ # Return first preference even if we can't verify availability
44
+ return fonts[0] if fonts else "Courier"
45
+
46
+
47
+ def _is_font_available(font_name: str) -> bool:
48
+ """Check if a font is available on the system.
49
+
50
+ Args:
51
+ font_name: Name of the font to check.
52
+
53
+ Returns:
54
+ True if font appears to be available.
55
+ """
56
+ try:
57
+ # Try to load font using PIL
58
+ ImageFont.truetype(font_name, 12)
59
+ return True
60
+ except (OSError, IOError):
61
+ pass
62
+
63
+ # Check common font paths by platform
64
+ system = platform.system().lower()
65
+
66
+ if system == "darwin":
67
+ font_dirs = [
68
+ Path("/System/Library/Fonts"),
69
+ Path("/Library/Fonts"),
70
+ Path.home() / "Library/Fonts",
71
+ ]
72
+ elif system == "linux":
73
+ font_dirs = [
74
+ Path("/usr/share/fonts"),
75
+ Path("/usr/local/share/fonts"),
76
+ Path.home() / ".fonts",
77
+ Path.home() / ".local/share/fonts",
78
+ ]
79
+ elif system == "windows":
80
+ font_dirs = [
81
+ Path("C:/Windows/Fonts"),
82
+ ]
83
+ else:
84
+ return False
85
+
86
+ # Simple check - look for files containing font name
87
+ font_name_lower = font_name.lower().replace(" ", "")
88
+ for font_dir in font_dirs:
89
+ if font_dir.exists():
90
+ for font_file in font_dir.rglob("*"):
91
+ if font_name_lower in font_file.stem.lower().replace(" ", ""):
92
+ return True
93
+
94
+ return False
95
+
96
+
97
+ # Default font determined at module load time
98
+ DEFAULT_FONT = get_default_monospace_font()
99
+
100
+
101
+ @dataclass
102
+ class CodeStyleConfig:
103
+ """Configuration for code block rendering."""
104
+ enabled: bool = True
105
+ theme: str = "default"
106
+ font_name: str = field(default_factory=lambda: DEFAULT_FONT)
107
+ font_size: int = 12
108
+ line_numbers: bool = False
109
+
110
+ @classmethod
111
+ def from_dict(cls, data: dict) -> "CodeStyleConfig":
112
+ """Create config from dictionary."""
113
+ return cls(
114
+ enabled=data.get("enabled", True),
115
+ theme=data.get("theme", "default"),
116
+ font_name=data.get("font_name", DEFAULT_FONT),
117
+ font_size=data.get("font_size", 12),
118
+ line_numbers=data.get("line_numbers", False),
119
+ )
120
+
121
+
122
+ @dataclass
123
+ class CodeBlock:
124
+ """Represents an extracted code block."""
125
+ code: str
126
+ language: str
127
+ start_pos: int = 0
128
+ end_pos: int = 0
129
+ original_text: str = ""
130
+
131
+
132
+ # Language aliases mapping
133
+ LANGUAGE_ALIASES = {
134
+ # Python
135
+ "py": "python",
136
+ "python3": "python",
137
+ # JavaScript
138
+ "js": "javascript",
139
+ "node": "javascript",
140
+ # TypeScript
141
+ "ts": "typescript",
142
+ # Shell
143
+ "sh": "bash",
144
+ "shell": "bash",
145
+ "zsh": "bash",
146
+ # YAML
147
+ "yml": "yaml",
148
+ # C++
149
+ "c++": "cpp",
150
+ # C#
151
+ "cs": "csharp",
152
+ "c#": "csharp",
153
+ # Ruby
154
+ "rb": "ruby",
155
+ # Kotlin
156
+ "kt": "kotlin",
157
+ # Markdown
158
+ "md": "markdown",
159
+ }
160
+
161
+ # Languages to exclude (handled by other renderers)
162
+ EXCLUDED_LANGUAGES = {"mermaid", "plantuml", "tree", "directory", "graphviz", "dot"}
163
+
164
+
165
+ def detect_language(marker: Optional[str]) -> str:
166
+ """Detect language from fenced code block marker.
167
+
168
+ Args:
169
+ marker: Language marker from code fence (e.g., 'python', 'js')
170
+
171
+ Returns:
172
+ Normalized language name, or 'text' for unknown/empty markers.
173
+ """
174
+ if not marker:
175
+ return "text"
176
+
177
+ marker = marker.lower().strip()
178
+
179
+ if not marker:
180
+ return "text"
181
+
182
+ # Check aliases first
183
+ if marker in LANGUAGE_ALIASES:
184
+ return LANGUAGE_ALIASES[marker]
185
+
186
+ # Try to get lexer to verify language exists
187
+ try:
188
+ get_lexer_by_name(marker)
189
+ return marker
190
+ except ClassNotFound:
191
+ return "text"
192
+
193
+
194
+ def get_available_themes() -> List[str]:
195
+ """Get list of available Pygments themes.
196
+
197
+ Returns:
198
+ List of theme names.
199
+ """
200
+ return list(get_all_styles())
201
+
202
+
203
+ def render_code_to_image(
204
+ code: str,
205
+ output_path: Path,
206
+ language: str = "text",
207
+ theme: str = "default",
208
+ font_name: str = None,
209
+ font_size: int = 12,
210
+ line_numbers: bool = False,
211
+ return_dimensions: bool = False,
212
+ ) -> Union[Path, Tuple[Path, int, int]]:
213
+ """Render code to a syntax-highlighted PNG image.
214
+
215
+ Args:
216
+ code: Source code to render.
217
+ output_path: Path for output PNG file.
218
+ language: Programming language for syntax highlighting.
219
+ theme: Pygments theme name.
220
+ font_name: Font name for rendering.
221
+ font_size: Font size in points.
222
+ line_numbers: Whether to show line numbers.
223
+ return_dimensions: If True, return (path, width, height).
224
+
225
+ Returns:
226
+ Output path, or tuple of (path, width, height) if return_dimensions=True.
227
+
228
+ Raises:
229
+ ValueError: If code is empty or theme is invalid.
230
+ """
231
+ if font_name is None:
232
+ font_name = DEFAULT_FONT
233
+
234
+ if not code or not code.strip():
235
+ raise ValueError("Code cannot be empty")
236
+
237
+ # Validate theme
238
+ available_themes = get_available_themes()
239
+ if theme not in available_themes:
240
+ raise ValueError(f"Invalid theme '{theme}'. Available themes: {', '.join(sorted(available_themes)[:10])}...")
241
+
242
+ # Get lexer
243
+ try:
244
+ lexer = get_lexer_by_name(language)
245
+ except ClassNotFound:
246
+ lexer = TextLexer()
247
+
248
+ # Get style
249
+ style = get_style_by_name(theme)
250
+
251
+ # Create formatter
252
+ formatter = ImageFormatter(
253
+ style=style,
254
+ font_name=font_name,
255
+ font_size=font_size,
256
+ line_numbers=line_numbers,
257
+ image_pad=10,
258
+ line_pad=2,
259
+ )
260
+
261
+ # Render
262
+ result = highlight(code, lexer, formatter)
263
+
264
+ # Write to file
265
+ output_path.parent.mkdir(parents=True, exist_ok=True)
266
+ with open(output_path, "wb") as f:
267
+ f.write(result)
268
+
269
+ if return_dimensions:
270
+ with Image.open(output_path) as img:
271
+ width, height = img.size
272
+ return output_path, width, height
273
+
274
+ return output_path
275
+
276
+
277
+ def extract_code_blocks(markdown_content: str) -> List[CodeBlock]:
278
+ """Extract code blocks from markdown content.
279
+
280
+ Excludes blocks handled by other renderers (mermaid, plantuml, tree, etc.).
281
+
282
+ Args:
283
+ markdown_content: Markdown text containing code blocks.
284
+
285
+ Returns:
286
+ List of CodeBlock objects.
287
+ """
288
+ # Pattern for fenced code blocks: ```language\ncode\n```
289
+ pattern = r'```(\w*)\n(.*?)```'
290
+
291
+ blocks = []
292
+ for match in re.finditer(pattern, markdown_content, re.DOTALL):
293
+ language = match.group(1).lower().strip()
294
+ code = match.group(2)
295
+
296
+ # Skip blocks handled by other renderers
297
+ if language in EXCLUDED_LANGUAGES:
298
+ continue
299
+
300
+ blocks.append(CodeBlock(
301
+ code=code.strip(),
302
+ language=language,
303
+ start_pos=match.start(),
304
+ end_pos=match.end(),
305
+ original_text=match.group(0),
306
+ ))
307
+
308
+ return blocks
309
+
310
+
311
+ def render_all_code_blocks(
312
+ markdown_content: str,
313
+ output_dir: Path,
314
+ config: Optional[CodeStyleConfig] = None,
315
+ ) -> dict:
316
+ """Render all code blocks in markdown to images.
317
+
318
+ Args:
319
+ markdown_content: Markdown text containing code blocks.
320
+ output_dir: Directory for output images.
321
+ config: Code style configuration.
322
+
323
+ Returns:
324
+ Dictionary mapping original code block text to image path.
325
+ """
326
+ if config is None:
327
+ config = CodeStyleConfig()
328
+
329
+ if not config.enabled:
330
+ return {}
331
+
332
+ blocks = extract_code_blocks(markdown_content)
333
+ result = {}
334
+
335
+ for i, block in enumerate(blocks):
336
+ output_path = output_dir / f"code_block_{i}.png"
337
+
338
+ # Detect language
339
+ language = detect_language(block.language) if block.language else "text"
340
+
341
+ try:
342
+ render_code_to_image(
343
+ code=block.code,
344
+ output_path=output_path,
345
+ language=language,
346
+ theme=config.theme,
347
+ font_name=config.font_name,
348
+ font_size=config.font_size,
349
+ line_numbers=config.line_numbers,
350
+ )
351
+ result[block.original_text] = output_path
352
+ except Exception as e:
353
+ # Log error but continue with other blocks
354
+ print(f"Warning: Failed to render code block {i}: {e}")
355
+
356
+ return result