@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,290 @@
1
+ """TOC style configuration module.
2
+
3
+ Provides dataclasses and functions for configuring Table of Contents styling.
4
+
5
+ Frontmatter example:
6
+ ```yaml
7
+ toc:
8
+ mode: static # or "dynamic" (default: static)
9
+ max_level: 3 # Maximum heading level to include (1-9, default: 3)
10
+ heading: "Table of Contents" # TOC heading text
11
+ tab_leader: dots # dots, dashes, underline, none
12
+ hyperlinks: true # Whether TOC entries are hyperlinks
13
+ styles:
14
+ 1:
15
+ bold: true
16
+ font_size: 12
17
+ indent: 0
18
+ 2:
19
+ bold: false
20
+ font_size: 11
21
+ indent: 12
22
+ 3:
23
+ italic: true
24
+ font_size: 10
25
+ indent: 24
26
+ ```
27
+ """
28
+ from dataclasses import dataclass, field
29
+ from enum import Enum
30
+ from typing import Any, Dict, List, Optional
31
+
32
+
33
+ class TocMode(Enum):
34
+ """TOC generation mode."""
35
+ STATIC = "static" # Generate actual TOC entries (works for PDF)
36
+ DYNAMIC = "dynamic" # Generate Word field code (requires Word to update)
37
+
38
+
39
+ @dataclass
40
+ class TocLevelStyle:
41
+ """Style configuration for a specific TOC level.
42
+
43
+ Attributes:
44
+ font_name: Font name for this level.
45
+ font_size: Font size in points.
46
+ bold: Whether text is bold.
47
+ italic: Whether text is italic.
48
+ color: Text color as hex string (without #).
49
+ indent: Indentation in points.
50
+ spacing_before: Spacing before in points.
51
+ spacing_after: Spacing after in points.
52
+ """
53
+ font_name: Optional[str] = None
54
+ font_size: Optional[int] = None
55
+ bold: Optional[bool] = None
56
+ italic: Optional[bool] = None
57
+ color: Optional[str] = None
58
+ indent: Optional[int] = None
59
+ spacing_before: Optional[int] = None
60
+ spacing_after: Optional[int] = None
61
+
62
+
63
+ @dataclass
64
+ class TocStyleConfig:
65
+ """Configuration for Table of Contents styling.
66
+
67
+ Attributes:
68
+ max_level: Maximum heading level to include (1-9).
69
+ show_page_numbers: Whether to show page numbers.
70
+ right_align_page_numbers: Whether to right-align page numbers.
71
+ tab_leader: Tab leader character type (dots, dashes, underline, none).
72
+ hyperlinks: Whether TOC entries are hyperlinks.
73
+ indent_per_level: Indentation per level in points.
74
+ level_styles: Per-level style configurations.
75
+ """
76
+ max_level: int = 3
77
+ show_page_numbers: bool = True
78
+ right_align_page_numbers: bool = True
79
+ tab_leader: str = "dots" # dots, dashes, underline, none
80
+ hyperlinks: bool = True
81
+ indent_per_level: int = 12
82
+ level_styles: Dict[int, TocLevelStyle] = field(default_factory=dict)
83
+
84
+ @classmethod
85
+ def from_dict(cls, style_dict: Dict[str, Any]) -> 'TocStyleConfig':
86
+ """Create TocStyleConfig from a dictionary.
87
+
88
+ Args:
89
+ style_dict: Dictionary with style properties.
90
+
91
+ Returns:
92
+ TocStyleConfig with values from dict.
93
+ """
94
+ level_styles = {}
95
+ levels_dict = style_dict.get('levels', {})
96
+ for level_key, level_dict in levels_dict.items():
97
+ try:
98
+ level_num = int(level_key)
99
+ level_styles[level_num] = TocLevelStyle(
100
+ font_name=level_dict.get('font_name'),
101
+ font_size=level_dict.get('font_size'),
102
+ bold=level_dict.get('bold'),
103
+ italic=level_dict.get('italic'),
104
+ color=level_dict.get('color'),
105
+ indent=level_dict.get('indent'),
106
+ spacing_before=level_dict.get('spacing_before'),
107
+ spacing_after=level_dict.get('spacing_after'),
108
+ )
109
+ except (ValueError, TypeError):
110
+ pass
111
+
112
+ return cls(
113
+ max_level=style_dict.get('max_level', 3),
114
+ show_page_numbers=style_dict.get('show_page_numbers', True),
115
+ right_align_page_numbers=style_dict.get('right_align_page_numbers', True),
116
+ tab_leader=style_dict.get('tab_leader', 'dots'),
117
+ hyperlinks=style_dict.get('hyperlinks', True),
118
+ indent_per_level=style_dict.get('indent_per_level', 12),
119
+ level_styles=level_styles,
120
+ )
121
+
122
+ def merge(self, override: 'TocStyleConfig') -> 'TocStyleConfig':
123
+ """Merge this config with an override config.
124
+
125
+ Args:
126
+ override: TocStyleConfig with override values.
127
+
128
+ Returns:
129
+ New TocStyleConfig with merged values.
130
+ """
131
+ default = TocStyleConfig()
132
+
133
+ # Merge level styles
134
+ merged_levels = {**self.level_styles}
135
+ for level, style in override.level_styles.items():
136
+ merged_levels[level] = style
137
+
138
+ return TocStyleConfig(
139
+ max_level=override.max_level if override.max_level != default.max_level else self.max_level,
140
+ show_page_numbers=override.show_page_numbers if override.show_page_numbers != default.show_page_numbers else self.show_page_numbers,
141
+ right_align_page_numbers=override.right_align_page_numbers if override.right_align_page_numbers != default.right_align_page_numbers else self.right_align_page_numbers,
142
+ tab_leader=override.tab_leader if override.tab_leader != default.tab_leader else self.tab_leader,
143
+ hyperlinks=override.hyperlinks if override.hyperlinks != default.hyperlinks else self.hyperlinks,
144
+ indent_per_level=override.indent_per_level if override.indent_per_level != default.indent_per_level else self.indent_per_level,
145
+ level_styles=merged_levels,
146
+ )
147
+
148
+
149
+ @dataclass
150
+ class TocConfig:
151
+ """Complete TOC configuration including mode and styles.
152
+
153
+ Attributes:
154
+ enabled: Whether TOC is enabled.
155
+ mode: TOC generation mode (static or dynamic).
156
+ heading: TOC heading text.
157
+ style: Style configuration for the TOC.
158
+ """
159
+ enabled: bool = True
160
+ mode: TocMode = TocMode.STATIC
161
+ heading: str = "Tartalomjegyzék"
162
+ style: TocStyleConfig = field(default_factory=TocStyleConfig)
163
+
164
+ @classmethod
165
+ def from_dict(cls, toc_dict: Dict[str, Any]) -> 'TocConfig':
166
+ """Create TocConfig from a dictionary (frontmatter).
167
+
168
+ Args:
169
+ toc_dict: Dictionary with TOC configuration.
170
+
171
+ Returns:
172
+ TocConfig with values from dict.
173
+ """
174
+ if not toc_dict:
175
+ return cls()
176
+
177
+ # Parse mode
178
+ mode_str = toc_dict.get('mode', 'static').lower()
179
+ mode = TocMode.DYNAMIC if mode_str == 'dynamic' else TocMode.STATIC
180
+
181
+ # Parse style configuration
182
+ style_dict = {
183
+ 'max_level': toc_dict.get('max_level', 3),
184
+ 'tab_leader': toc_dict.get('tab_leader', 'dots'),
185
+ 'hyperlinks': toc_dict.get('hyperlinks', True),
186
+ 'show_page_numbers': toc_dict.get('show_page_numbers', True),
187
+ 'right_align_page_numbers': toc_dict.get('right_align_page_numbers', True),
188
+ 'indent_per_level': toc_dict.get('indent_per_level', 12),
189
+ }
190
+
191
+ # Parse level styles from 'styles' key
192
+ if 'styles' in toc_dict and isinstance(toc_dict['styles'], dict):
193
+ style_dict['levels'] = toc_dict['styles']
194
+
195
+ style = TocStyleConfig.from_dict(style_dict)
196
+
197
+ return cls(
198
+ enabled=toc_dict.get('enabled', True),
199
+ mode=mode,
200
+ heading=toc_dict.get('heading', 'Tartalomjegyzék'),
201
+ style=style,
202
+ )
203
+
204
+
205
+ # Default TOC style configuration
206
+ DEFAULT_TOC_STYLE = TocStyleConfig()
207
+
208
+ # Default TOC configuration
209
+ DEFAULT_TOC_CONFIG = TocConfig()
210
+
211
+
212
+ def get_tab_leader_char(leader_type: str) -> str:
213
+ """Get the tab leader character for a given type.
214
+
215
+ Args:
216
+ leader_type: Type of tab leader (dots, dashes, underline, none).
217
+
218
+ Returns:
219
+ Character to use for tab leader.
220
+ """
221
+ leaders = {
222
+ 'dots': '.',
223
+ 'dashes': '-',
224
+ 'underline': '_',
225
+ 'none': ' ',
226
+ }
227
+ return leaders.get(leader_type.lower(), '.')
228
+
229
+
230
+ def extract_toc_style(frontmatter: Dict[str, Any]) -> Optional[TocStyleConfig]:
231
+ """Extract TOC style configuration from frontmatter.
232
+
233
+ Args:
234
+ frontmatter: Parsed frontmatter dictionary.
235
+
236
+ Returns:
237
+ TocStyleConfig if toc_style is present, None otherwise.
238
+ """
239
+ toc_style_dict = frontmatter.get('toc_style')
240
+ if toc_style_dict and isinstance(toc_style_dict, dict):
241
+ return TocStyleConfig.from_dict(toc_style_dict)
242
+ return None
243
+
244
+
245
+ def extract_toc_config(frontmatter: Dict[str, Any]) -> TocConfig:
246
+ """Extract complete TOC configuration from frontmatter.
247
+
248
+ Supports the 'toc' key in frontmatter with the following structure:
249
+ ```yaml
250
+ toc:
251
+ mode: static # or "dynamic"
252
+ max_level: 3
253
+ heading: "Table of Contents"
254
+ tab_leader: dots
255
+ hyperlinks: true
256
+ styles:
257
+ 1:
258
+ bold: true
259
+ font_size: 12
260
+ 2:
261
+ bold: false
262
+ font_size: 11
263
+ ```
264
+
265
+ Args:
266
+ frontmatter: Parsed frontmatter dictionary.
267
+
268
+ Returns:
269
+ TocConfig with values from frontmatter, or defaults.
270
+ """
271
+ toc_dict = frontmatter.get('toc')
272
+
273
+ # Also check for legacy 'toc_style' key and merge
274
+ legacy_style = frontmatter.get('toc_style')
275
+
276
+ if toc_dict and isinstance(toc_dict, dict):
277
+ config = TocConfig.from_dict(toc_dict)
278
+
279
+ # Merge legacy toc_style if present
280
+ if legacy_style and isinstance(legacy_style, dict):
281
+ legacy_config = TocStyleConfig.from_dict(legacy_style)
282
+ config.style = config.style.merge(legacy_config)
283
+
284
+ return config
285
+ elif legacy_style and isinstance(legacy_style, dict):
286
+ # Only legacy toc_style present
287
+ style = TocStyleConfig.from_dict(legacy_style)
288
+ return TocConfig(style=style)
289
+
290
+ return DEFAULT_TOC_CONFIG
@@ -0,0 +1,328 @@
1
+ """Tree renderer - converts ASCII tree structures to PNG images."""
2
+ import re
3
+ from dataclasses import dataclass, field
4
+ from pathlib import Path
5
+ from typing import List, Optional, Tuple, Union
6
+
7
+ from PIL import Image, ImageDraw, ImageFont
8
+
9
+ from .code_renderer import DEFAULT_FONT, get_default_monospace_font
10
+
11
+
12
+ @dataclass
13
+ class TreeStyleConfig:
14
+ """Configuration for tree rendering."""
15
+ enabled: bool = True
16
+ auto_detect: bool = True
17
+ font_name: str = field(default_factory=lambda: DEFAULT_FONT)
18
+ font_size: int = 12
19
+
20
+ @classmethod
21
+ def from_dict(cls, data: dict) -> "TreeStyleConfig":
22
+ """Create config from dictionary."""
23
+ return cls(
24
+ enabled=data.get("enabled", True),
25
+ auto_detect=data.get("auto_detect", True),
26
+ font_name=data.get("font_name", DEFAULT_FONT),
27
+ font_size=data.get("font_size", 12),
28
+ )
29
+
30
+
31
+ @dataclass
32
+ class TreeNode:
33
+ """Represents a node in the tree structure."""
34
+ name: str
35
+ children: List["TreeNode"] = field(default_factory=list)
36
+ depth: int = 0
37
+
38
+
39
+ @dataclass
40
+ class TreeBlock:
41
+ """Represents an extracted tree block."""
42
+ code: str
43
+ start_pos: int = 0
44
+ end_pos: int = 0
45
+ original_text: str = ""
46
+
47
+
48
+ # Unicode box-drawing characters
49
+ BOX_CHARS_UNICODE = r'[├└│─┌┐┘┬┴┼]'
50
+ # ASCII approximations
51
+ BOX_CHARS_ASCII = r'[\|+`]'
52
+
53
+
54
+ def is_ascii_tree(code: str) -> bool:
55
+ """Detect if code block contains an ASCII tree structure.
56
+
57
+ Uses heuristic: 5+ lines must contain box-drawing characters.
58
+
59
+ Args:
60
+ code: Code block content.
61
+
62
+ Returns:
63
+ True if code appears to be an ASCII tree.
64
+ """
65
+ if not code or not code.strip():
66
+ return False
67
+
68
+ lines = code.strip().split('\n')
69
+
70
+ if len(lines) < 5:
71
+ return False
72
+
73
+ # Count lines with box-drawing characters
74
+ tree_lines = 0
75
+ for line in lines:
76
+ if re.search(BOX_CHARS_UNICODE, line):
77
+ tree_lines += 1
78
+ elif re.search(r'[+|`].*[-|`]', line) or re.search(r'^[\s]*[+|`\\]', line):
79
+ # ASCII approximation patterns
80
+ tree_lines += 1
81
+
82
+ return tree_lines >= 5
83
+
84
+
85
+ def is_tree_block(language: Optional[str]) -> bool:
86
+ """Check if language marker indicates a tree block.
87
+
88
+ Args:
89
+ language: Language marker from code fence.
90
+
91
+ Returns:
92
+ True if marker is 'tree' or 'directory'.
93
+ """
94
+ if not language:
95
+ return False
96
+
97
+ return language.lower().strip() in ("tree", "directory")
98
+
99
+
100
+ def parse_tree(tree_text: str) -> Optional[TreeNode]:
101
+ """Parse ASCII tree text into a tree structure.
102
+
103
+ Args:
104
+ tree_text: ASCII tree text.
105
+
106
+ Returns:
107
+ Root TreeNode, or None if parsing fails.
108
+ """
109
+ if not tree_text or not tree_text.strip():
110
+ return None
111
+
112
+ lines = tree_text.strip().split('\n')
113
+ if not lines:
114
+ return None
115
+
116
+ # First line is the root
117
+ root_name = lines[0].strip()
118
+ # Remove any leading tree characters
119
+ root_name = re.sub(r'^[├└│─┌┐┘┬┴┼\s+|`\\-]+', '', root_name).strip()
120
+ if not root_name:
121
+ root_name = lines[0].strip()
122
+
123
+ root = TreeNode(name=root_name, depth=0)
124
+
125
+ if len(lines) == 1:
126
+ return root
127
+
128
+ # Parse remaining lines
129
+ node_stack = [(root, -1)] # (node, indent_level)
130
+
131
+ for line in lines[1:]:
132
+ if not line.strip():
133
+ continue
134
+
135
+ # Calculate indent level by finding the position of the first non-space, non-tree char
136
+ # Tree chars: ├ └ │ ─ + | ` \ -
137
+ stripped = line.lstrip()
138
+ indent = len(line) - len(stripped)
139
+
140
+ # Find the actual name (after tree drawing chars)
141
+ name_match = re.search(r'[├└│+|`\\─\-\s]*([\w\.\-_/]+.*?)$', stripped)
142
+ if name_match:
143
+ name = name_match.group(1).strip()
144
+ else:
145
+ name = stripped
146
+
147
+ # Clean up the name
148
+ name = re.sub(r'^[─\-\s]+', '', name).strip()
149
+ if not name:
150
+ continue
151
+
152
+ new_node = TreeNode(name=name, depth=indent)
153
+
154
+ # Find parent based on indent
155
+ while node_stack and node_stack[-1][1] >= indent:
156
+ node_stack.pop()
157
+
158
+ if node_stack:
159
+ parent = node_stack[-1][0]
160
+ parent.children.append(new_node)
161
+
162
+ node_stack.append((new_node, indent))
163
+
164
+ return root
165
+
166
+
167
+ def render_tree_to_image(
168
+ tree_text: str,
169
+ output_path: Path,
170
+ font_name: str = None,
171
+ font_size: int = 12,
172
+ return_dimensions: bool = False,
173
+ ) -> Union[Path, Tuple[Path, int, int]]:
174
+ """Render ASCII tree to a PNG image.
175
+
176
+ Args:
177
+ tree_text: ASCII tree text.
178
+ output_path: Path for output PNG file.
179
+ font_name: Font name for rendering.
180
+ font_size: Font size in points.
181
+ return_dimensions: If True, return (path, width, height).
182
+
183
+ Returns:
184
+ Output path, or tuple of (path, width, height) if return_dimensions=True.
185
+
186
+ Raises:
187
+ ValueError: If tree_text is empty.
188
+ """
189
+ if font_name is None:
190
+ font_name = DEFAULT_FONT
191
+
192
+ if not tree_text or not tree_text.strip():
193
+ raise ValueError("Tree text cannot be empty")
194
+
195
+ # Try to load font
196
+ try:
197
+ font = ImageFont.truetype(font_name, font_size)
198
+ except OSError:
199
+ # Fallback to platform default font
200
+ try:
201
+ fallback_font = get_default_monospace_font()
202
+ font = ImageFont.truetype(fallback_font, font_size)
203
+ except OSError:
204
+ font = ImageFont.load_default()
205
+
206
+ lines = tree_text.strip().split('\n')
207
+
208
+ # Calculate dimensions
209
+ padding = 20
210
+ line_height = font_size + 4
211
+
212
+ # Measure text width
213
+ dummy_img = Image.new('RGB', (1, 1))
214
+ draw = ImageDraw.Draw(dummy_img)
215
+
216
+ max_width = 0
217
+ for line in lines:
218
+ bbox = draw.textbbox((0, 0), line, font=font)
219
+ width = bbox[2] - bbox[0]
220
+ max_width = max(max_width, width)
221
+
222
+ img_width = max_width + 2 * padding
223
+ img_height = len(lines) * line_height + 2 * padding
224
+
225
+ # Create image
226
+ img = Image.new('RGB', (img_width, img_height), color='white')
227
+ draw = ImageDraw.Draw(img)
228
+
229
+ # Draw text
230
+ y = padding
231
+ for line in lines:
232
+ draw.text((padding, y), line, font=font, fill='black')
233
+ y += line_height
234
+
235
+ # Save
236
+ output_path.parent.mkdir(parents=True, exist_ok=True)
237
+ img.save(output_path, 'PNG')
238
+
239
+ if return_dimensions:
240
+ return output_path, img_width, img_height
241
+
242
+ return output_path
243
+
244
+
245
+ def extract_tree_blocks(
246
+ markdown_content: str,
247
+ config: Optional[TreeStyleConfig] = None,
248
+ ) -> List[TreeBlock]:
249
+ """Extract tree blocks from markdown content.
250
+
251
+ Args:
252
+ markdown_content: Markdown text containing code blocks.
253
+ config: Tree style configuration.
254
+
255
+ Returns:
256
+ List of TreeBlock objects.
257
+ """
258
+ if config is None:
259
+ config = TreeStyleConfig()
260
+
261
+ # Pattern for fenced code blocks
262
+ pattern = r'```(\w*)\n(.*?)```'
263
+
264
+ blocks = []
265
+ for match in re.finditer(pattern, markdown_content, re.DOTALL):
266
+ language = match.group(1).lower().strip()
267
+ code = match.group(2)
268
+
269
+ # Check if explicitly marked as tree
270
+ if is_tree_block(language):
271
+ blocks.append(TreeBlock(
272
+ code=code.strip(),
273
+ start_pos=match.start(),
274
+ end_pos=match.end(),
275
+ original_text=match.group(0),
276
+ ))
277
+ # Auto-detect trees in unmarked code blocks
278
+ elif config.auto_detect and not language and is_ascii_tree(code):
279
+ blocks.append(TreeBlock(
280
+ code=code.strip(),
281
+ start_pos=match.start(),
282
+ end_pos=match.end(),
283
+ original_text=match.group(0),
284
+ ))
285
+
286
+ return blocks
287
+
288
+
289
+ def render_all_tree_blocks(
290
+ markdown_content: str,
291
+ output_dir: Path,
292
+ config: Optional[TreeStyleConfig] = None,
293
+ ) -> dict:
294
+ """Render all tree blocks in markdown to images.
295
+
296
+ Args:
297
+ markdown_content: Markdown text containing tree blocks.
298
+ output_dir: Directory for output images.
299
+ config: Tree style configuration.
300
+
301
+ Returns:
302
+ Dictionary mapping original tree block text to image path.
303
+ """
304
+ if config is None:
305
+ config = TreeStyleConfig()
306
+
307
+ if not config.enabled:
308
+ return {}
309
+
310
+ blocks = extract_tree_blocks(markdown_content, config)
311
+ result = {}
312
+
313
+ for i, block in enumerate(blocks):
314
+ output_path = output_dir / f"tree_block_{i}.png"
315
+
316
+ try:
317
+ render_tree_to_image(
318
+ tree_text=block.code,
319
+ output_path=output_path,
320
+ font_name=config.font_name,
321
+ font_size=config.font_size,
322
+ )
323
+ result[block.original_text] = output_path
324
+ except Exception as e:
325
+ # Log error but continue with other blocks
326
+ print(f"Warning: Failed to render tree block {i}: {e}")
327
+
328
+ return result