@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,644 @@
1
+ """Frontmatter parser module for extracting metadata from Markdown and AsciiDoc files.
2
+
3
+ This module provides functions to parse YAML frontmatter from Markdown files
4
+ and native attributes from AsciiDoc files, extracting template configuration,
5
+ variables, and conversion options.
6
+ """
7
+ import logging
8
+ import re
9
+ from typing import Any, Dict, List, Set, Tuple
10
+
11
+ import yaml
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ # Known option keys for frontmatter
16
+ KNOWN_OPTION_KEYS: Set[str] = {
17
+ # Template configuration
18
+ 'template',
19
+ 'templates_dir',
20
+
21
+ # Document metadata
22
+ 'language',
23
+ 'document_name',
24
+ 'document_title',
25
+
26
+ # Cover page options
27
+ 'enable_cover_page',
28
+
29
+ # TOC options
30
+ 'enable_toc',
31
+ 'toc_heading',
32
+ 'toc_style',
33
+
34
+ # Diagram options
35
+ 'diagram_format',
36
+ 'diagram_width',
37
+ 'diagram_scale',
38
+ 'embed_svg_in_word',
39
+ 'diagrams', # New: diagram sizing configuration section
40
+
41
+ # Code block rendering options
42
+ 'code_style', # Code syntax highlighting configuration
43
+ 'tree_style', # ASCII tree rendering configuration
44
+
45
+ # Font options
46
+ 'font_name',
47
+ 'embed_fonts',
48
+
49
+ # Styling options
50
+ 'table_style',
51
+ 'table_profiles', # Column width profiles for different table types
52
+ 'image_style',
53
+ 'logos',
54
+
55
+ # Debug options
56
+ 'debug',
57
+ }
58
+
59
+ # Conversion option keys (subset of known keys)
60
+ CONVERSION_OPTION_KEYS: Set[str] = {
61
+ 'enable_toc',
62
+ 'enable_cover_page',
63
+ 'toc_heading',
64
+ 'diagram_format',
65
+ 'diagram_width',
66
+ 'diagram_scale',
67
+ 'embed_svg_in_word',
68
+ 'font_name',
69
+ 'embed_fonts',
70
+ 'debug',
71
+ }
72
+
73
+ # Template configuration keys
74
+ TEMPLATE_CONFIG_KEYS: Set[str] = {
75
+ 'template',
76
+ 'templates_dir',
77
+ }
78
+
79
+
80
+ def parse_yaml_frontmatter(content: str) -> Tuple[Dict[str, Any], str]:
81
+ """Parse YAML frontmatter from Markdown content.
82
+
83
+ Args:
84
+ content: The full Markdown file content.
85
+
86
+ Returns:
87
+ A tuple of (metadata dict, remaining content without frontmatter).
88
+ If no frontmatter is found or parsing fails, returns ({}, original content).
89
+ """
90
+ if not content.startswith('---'):
91
+ return {}, content
92
+
93
+ # Find the closing delimiter
94
+ lines = content.split('\n')
95
+ end_index = None
96
+
97
+ for i, line in enumerate(lines[1:], start=1):
98
+ if line.strip() == '---':
99
+ end_index = i
100
+ break
101
+
102
+ if end_index is None:
103
+ # No closing delimiter found
104
+ return {}, content
105
+
106
+ # Extract YAML content
107
+ yaml_content = '\n'.join(lines[1:end_index])
108
+ remaining_content = '\n'.join(lines[end_index + 1:])
109
+
110
+ try:
111
+ metadata = yaml.safe_load(yaml_content)
112
+ if metadata is None:
113
+ metadata = {}
114
+ return metadata, remaining_content
115
+ except yaml.YAMLError as e:
116
+ logger.warning(f"Warning: Failed to parse YAML frontmatter: {e}")
117
+ return {}, content
118
+
119
+
120
+ def parse_asciidoc_attributes(content: str) -> Tuple[Dict[str, Any], str]:
121
+ """Parse native AsciiDoc attributes from content.
122
+
123
+ Parses attributes in the format `:key: value` at the beginning of the file.
124
+ Stops parsing at the first non-attribute, non-blank line.
125
+
126
+ Args:
127
+ content: The full AsciiDoc file content.
128
+
129
+ Returns:
130
+ A tuple of (metadata dict, remaining content without attributes).
131
+ """
132
+ lines = content.split('\n')
133
+ metadata: Dict[str, Any] = {}
134
+ attribute_end_index = 0
135
+
136
+ # Regex pattern for AsciiDoc attributes
137
+ attr_pattern = re.compile(r'^:([a-zA-Z_][a-zA-Z0-9_-]*):\s*(.*)$')
138
+
139
+ for i, line in enumerate(lines):
140
+ stripped = line.strip()
141
+
142
+ # Empty lines are allowed between attributes
143
+ if not stripped:
144
+ attribute_end_index = i + 1
145
+ continue
146
+
147
+ match = attr_pattern.match(stripped)
148
+ if match:
149
+ key = match.group(1)
150
+ value = match.group(2).strip()
151
+
152
+ # Convert boolean-like values
153
+ value = _convert_asciidoc_value(value)
154
+
155
+ metadata[key] = value
156
+ attribute_end_index = i + 1
157
+ else:
158
+ # First non-attribute line - stop parsing
159
+ break
160
+
161
+ remaining_content = '\n'.join(lines[attribute_end_index:])
162
+ return metadata, remaining_content
163
+
164
+
165
+ def _convert_asciidoc_value(value: str) -> Any:
166
+ """Convert AsciiDoc attribute value to appropriate Python type.
167
+
168
+ Args:
169
+ value: The string value from an AsciiDoc attribute.
170
+
171
+ Returns:
172
+ The converted value (bool, int, float, or original string).
173
+ """
174
+ lower_value = value.lower()
175
+
176
+ # Boolean conversion
177
+ if lower_value in ('true', 'yes'):
178
+ return True
179
+ if lower_value in ('false', 'no'):
180
+ return False
181
+
182
+ # Integer conversion
183
+ try:
184
+ return int(value)
185
+ except ValueError:
186
+ pass
187
+
188
+ # Float conversion
189
+ try:
190
+ return float(value)
191
+ except ValueError:
192
+ pass
193
+
194
+ return value
195
+
196
+
197
+ def parse_frontmatter(content: str, format: str = 'markdown') -> Tuple[Dict[str, Any], str]:
198
+ """Parse frontmatter from content based on format.
199
+
200
+ Automatically detects YAML frontmatter (starting with ---) even in AsciiDoc files.
201
+
202
+ Args:
203
+ content: The full file content.
204
+ format: The file format ('markdown' or 'asciidoc').
205
+
206
+ Returns:
207
+ A tuple of (metadata dict, remaining content without frontmatter).
208
+ """
209
+ # YAML frontmatter takes precedence (even in AsciiDoc files)
210
+ if content.startswith('---'):
211
+ return parse_yaml_frontmatter(content)
212
+
213
+ # For AsciiDoc, try native attributes
214
+ if format.lower() in ('asciidoc', 'adoc'):
215
+ return parse_asciidoc_attributes(content)
216
+
217
+ # For Markdown without YAML frontmatter, return empty
218
+ return {}, content
219
+
220
+
221
+ def extract_template_config(metadata: Dict[str, Any]) -> Dict[str, Any]:
222
+ """Extract template configuration from metadata.
223
+
224
+ Args:
225
+ metadata: The parsed frontmatter metadata.
226
+
227
+ Returns:
228
+ Dictionary containing only template configuration keys.
229
+ """
230
+ return {k: v for k, v in metadata.items() if k in TEMPLATE_CONFIG_KEYS}
231
+
232
+
233
+ def extract_variables(metadata: Dict[str, Any], known_vars: List[str] = None) -> Dict[str, str]:
234
+ """Extract template variables from metadata.
235
+
236
+ Extracts variables from:
237
+ 1. The nested 'variables' section (preferred)
238
+ 2. Top-level keys that are in known_vars and not system option keys
239
+
240
+ Args:
241
+ metadata: The parsed frontmatter metadata.
242
+ known_vars: Optional list of known template variable names.
243
+
244
+ Returns:
245
+ Dictionary of variable name to value mappings.
246
+ """
247
+ result = {}
248
+
249
+ # First, extract from nested 'variables' section (preferred method)
250
+ variables_section = metadata.get('variables', {})
251
+ if isinstance(variables_section, dict):
252
+ for key, value in variables_section.items():
253
+ if value is not None:
254
+ result[key] = str(value) if not isinstance(value, str) else value
255
+
256
+ # Then, extract top-level keys (for backward compatibility)
257
+ known_set = set(known_vars) if known_vars else set()
258
+ for key, value in metadata.items():
259
+ # Skip system option keys and special sections
260
+ if key in KNOWN_OPTION_KEYS or key in ('variables', 'logos', 'table_style', 'table_profiles', 'toc', 'images'):
261
+ continue
262
+ # Only include if it's a known variable (when known_vars provided)
263
+ if known_vars is None or key in known_set:
264
+ if key not in result: # Don't override variables section
265
+ result[key] = str(value) if not isinstance(value, str) else value
266
+
267
+ return result
268
+
269
+
270
+ def extract_conversion_options(metadata: Dict[str, Any]) -> Dict[str, Any]:
271
+ """Extract conversion options from metadata.
272
+
273
+ Args:
274
+ metadata: The parsed frontmatter metadata.
275
+
276
+ Returns:
277
+ Dictionary containing only conversion option keys.
278
+ """
279
+ return {k: v for k, v in metadata.items() if k in CONVERSION_OPTION_KEYS}
280
+
281
+
282
+ def extract_table_style(metadata: Dict[str, Any]) -> Dict[str, Any]:
283
+ """Extract table style configuration from metadata.
284
+
285
+ Args:
286
+ metadata: The parsed frontmatter metadata.
287
+
288
+ Returns:
289
+ Dictionary containing table style options, or empty dict if not present.
290
+ """
291
+ return metadata.get('table_style', {})
292
+
293
+
294
+ def extract_table_profiles(metadata: Dict[str, Any]) -> Dict[str, Dict[str, float]]:
295
+ """Extract table column width profiles from metadata.
296
+
297
+ Table profiles define column width multipliers for different table types,
298
+ identified by their header columns. When a table's headers match a profile,
299
+ the corresponding column widths are applied.
300
+
301
+ Example frontmatter:
302
+ table_profiles:
303
+ attributes:
304
+ columns: ["Név", "Típus", "Leírás", "Kötelező"]
305
+ widths: [1.0, 0.7, 2.5, 0.5]
306
+ operations:
307
+ columns: ["Művelet", "Leírás", "Állapotátmenet"]
308
+ widths: [1.0, 2.0, 1.5]
309
+
310
+ Args:
311
+ metadata: The parsed frontmatter metadata.
312
+
313
+ Returns:
314
+ Dictionary mapping profile names to column width dicts.
315
+ Each profile is a dict mapping column header text to width multiplier.
316
+ """
317
+ profiles_raw = metadata.get('table_profiles', {})
318
+ profiles: Dict[str, Dict[str, float]] = {}
319
+
320
+ if not isinstance(profiles_raw, dict):
321
+ return profiles
322
+
323
+ for profile_name, profile_data in profiles_raw.items():
324
+ if not isinstance(profile_data, dict):
325
+ continue
326
+
327
+ columns = profile_data.get('columns', [])
328
+ widths = profile_data.get('widths', [])
329
+
330
+ if not columns or not widths or len(columns) != len(widths):
331
+ logger.warning(f"Invalid table profile '{profile_name}': columns and widths must match")
332
+ continue
333
+
334
+ # Build column -> width mapping
335
+ profile_widths: Dict[str, float] = {}
336
+ for col, width in zip(columns, widths):
337
+ try:
338
+ profile_widths[str(col)] = float(width)
339
+ except (ValueError, TypeError):
340
+ logger.warning(f"Invalid width value in profile '{profile_name}': {width}")
341
+ continue
342
+
343
+ if profile_widths:
344
+ profiles[profile_name] = profile_widths
345
+
346
+ return profiles
347
+
348
+
349
+ def extract_toc_style(metadata: Dict[str, Any]) -> Dict[str, Any]:
350
+ """Extract TOC style configuration from metadata.
351
+
352
+ Args:
353
+ metadata: The parsed frontmatter metadata.
354
+
355
+ Returns:
356
+ Dictionary containing TOC style options, or empty dict if not present.
357
+ """
358
+ return metadata.get('toc_style', {})
359
+
360
+
361
+ def extract_image_style(metadata: Dict[str, Any]) -> Dict[str, Any]:
362
+ """Extract image style configuration from metadata.
363
+
364
+ Args:
365
+ metadata: The parsed frontmatter metadata.
366
+
367
+ Returns:
368
+ Dictionary containing image style options, or empty dict if not present.
369
+ """
370
+ return metadata.get('image_style', {})
371
+
372
+
373
+ def get_known_option_keys() -> Set[str]:
374
+ """Get the set of known option keys.
375
+
376
+ Returns:
377
+ Set of all known frontmatter option keys.
378
+ """
379
+ return KNOWN_OPTION_KEYS.copy()
380
+
381
+
382
+ def warn_unknown_keys(metadata: Dict[str, Any], known_vars: List[str]) -> None:
383
+ """Log warnings for unknown keys in metadata.
384
+
385
+ Args:
386
+ metadata: The parsed frontmatter metadata.
387
+ known_vars: List of known template variable names.
388
+ """
389
+ known_set = KNOWN_OPTION_KEYS | set(known_vars)
390
+
391
+ for key in metadata.keys():
392
+ if key not in known_set:
393
+ logger.warning(f"Unknown frontmatter key: '{key}'")
394
+
395
+
396
+ def merge_with_defaults(frontmatter: Dict[str, Any], defaults: Dict[str, Any]) -> Dict[str, Any]:
397
+ """Merge frontmatter values with defaults.
398
+
399
+ Frontmatter values take priority over defaults. Nested dictionaries
400
+ are merged recursively.
401
+
402
+ Args:
403
+ frontmatter: The parsed frontmatter metadata.
404
+ defaults: Default values to use for missing keys.
405
+
406
+ Returns:
407
+ Merged dictionary with frontmatter taking priority.
408
+ """
409
+ result = defaults.copy()
410
+
411
+ for key, value in frontmatter.items():
412
+ if key in result and isinstance(result[key], dict) and isinstance(value, dict):
413
+ # Recursive merge for nested dicts
414
+ result[key] = _merge_dicts(result[key], value)
415
+ else:
416
+ result[key] = value
417
+
418
+ return result
419
+
420
+
421
+ def _merge_dicts(base: Dict[str, Any], override: Dict[str, Any]) -> Dict[str, Any]:
422
+ """Recursively merge two dictionaries.
423
+
424
+ Args:
425
+ base: The base dictionary (defaults).
426
+ override: The override dictionary (takes priority).
427
+
428
+ Returns:
429
+ Merged dictionary.
430
+ """
431
+ result = base.copy()
432
+
433
+ for key, value in override.items():
434
+ if key in result and isinstance(result[key], dict) and isinstance(value, dict):
435
+ result[key] = _merge_dicts(result[key], value)
436
+ else:
437
+ result[key] = value
438
+
439
+ return result
440
+
441
+
442
+ def extract_code_style(metadata: Dict[str, Any]) -> Dict[str, Any]:
443
+ """Extract code block styling configuration from metadata.
444
+
445
+ Parses the 'code_style' section in frontmatter which controls how code
446
+ blocks are rendered as syntax-highlighted images using Pygments.
447
+
448
+ Expected frontmatter format:
449
+ ```yaml
450
+ code_style:
451
+ enabled: true # Enable code block rendering (default: true)
452
+ theme: default # Pygments theme name (default: "default")
453
+ font_name: Menlo # Monospace font for code (platform-specific default)
454
+ font_size: 12 # Font size in points (default: 12)
455
+ line_numbers: false # Show line numbers (default: false)
456
+ ```
457
+
458
+ Args:
459
+ metadata: The parsed frontmatter metadata.
460
+
461
+ Returns:
462
+ Dictionary containing code style configuration options.
463
+ """
464
+ code_style = metadata.get('code_style', {})
465
+ if not isinstance(code_style, dict):
466
+ return {}
467
+
468
+ result: Dict[str, Any] = {}
469
+
470
+ # Extract enabled flag
471
+ enabled = code_style.get('enabled')
472
+ if enabled is not None:
473
+ result['enabled'] = bool(enabled)
474
+
475
+ # Extract theme
476
+ theme = code_style.get('theme')
477
+ if theme is not None:
478
+ result['theme'] = str(theme)
479
+
480
+ # Extract font_name
481
+ font_name = code_style.get('font_name')
482
+ if font_name is not None:
483
+ result['font_name'] = str(font_name)
484
+
485
+ # Extract font_size
486
+ font_size = code_style.get('font_size')
487
+ if font_size is not None:
488
+ try:
489
+ result['font_size'] = int(font_size)
490
+ except (TypeError, ValueError):
491
+ logger.warning(f"Invalid font_size value: {font_size}")
492
+
493
+ # Extract line_numbers
494
+ line_numbers = code_style.get('line_numbers')
495
+ if line_numbers is not None:
496
+ result['line_numbers'] = bool(line_numbers)
497
+
498
+ return result
499
+
500
+
501
+ def extract_tree_style(metadata: Dict[str, Any]) -> Dict[str, Any]:
502
+ """Extract ASCII tree styling configuration from metadata.
503
+
504
+ Parses the 'tree_style' section in frontmatter which controls how ASCII
505
+ trees are detected and rendered as images using Pillow.
506
+
507
+ Expected frontmatter format:
508
+ ```yaml
509
+ tree_style:
510
+ enabled: true # Enable tree rendering (default: true)
511
+ auto_detect: true # Auto-detect trees in unmarked code blocks (default: true)
512
+ font_name: Menlo # Monospace font for trees (platform-specific default)
513
+ font_size: 12 # Font size in points (default: 12)
514
+ ```
515
+
516
+ Args:
517
+ metadata: The parsed frontmatter metadata.
518
+
519
+ Returns:
520
+ Dictionary containing tree style configuration options.
521
+ """
522
+ tree_style = metadata.get('tree_style', {})
523
+ if not isinstance(tree_style, dict):
524
+ return {}
525
+
526
+ result: Dict[str, Any] = {}
527
+
528
+ # Extract enabled flag
529
+ enabled = tree_style.get('enabled')
530
+ if enabled is not None:
531
+ result['enabled'] = bool(enabled)
532
+
533
+ # Extract auto_detect
534
+ auto_detect = tree_style.get('auto_detect')
535
+ if auto_detect is not None:
536
+ result['auto_detect'] = bool(auto_detect)
537
+
538
+ # Extract font_name
539
+ font_name = tree_style.get('font_name')
540
+ if font_name is not None:
541
+ result['font_name'] = str(font_name)
542
+
543
+ # Extract font_size
544
+ font_size = tree_style.get('font_size')
545
+ if font_size is not None:
546
+ try:
547
+ result['font_size'] = int(font_size)
548
+ except (TypeError, ValueError):
549
+ logger.warning(f"Invalid font_size value: {font_size}")
550
+
551
+ return result
552
+
553
+
554
+ def extract_diagram_config(metadata: Dict[str, Any]) -> Dict[str, Any]:
555
+ """Extract diagram sizing configuration from metadata.
556
+
557
+ Parses the 'diagrams' section in frontmatter which controls how diagrams
558
+ are sized for consistent visual scaling across different diagram tools
559
+ (Mermaid, PlantUML, Graphviz).
560
+
561
+ Expected frontmatter format:
562
+ ```yaml
563
+ diagrams:
564
+ sizing: consistent # or fixed, auto
565
+ min_scale: 0.3 # minimum scale factor (30%)
566
+ rotation: warn # or auto, none
567
+ page_width: 6.5 # available width in inches
568
+ page_height: 9.0 # available height in inches
569
+ mermaid:
570
+ font_size: 14 # standardized font size
571
+ plantuml:
572
+ font_size: 14
573
+ graphviz:
574
+ font_size: 14
575
+ ```
576
+
577
+ Args:
578
+ metadata: The parsed frontmatter metadata.
579
+
580
+ Returns:
581
+ Dictionary containing diagram configuration options.
582
+ Keys:
583
+ - sizing: 'consistent', 'fixed', or 'auto'
584
+ - min_scale: float (0.0-1.0)
585
+ - rotation: 'warn', 'auto', or 'none'
586
+ - page_width: float (inches)
587
+ - page_height: float (inches)
588
+ - mermaid: dict with tool-specific config
589
+ - plantuml: dict with tool-specific config
590
+ - graphviz: dict with tool-specific config
591
+ """
592
+ diagrams = metadata.get('diagrams', {})
593
+ if not isinstance(diagrams, dict):
594
+ return {}
595
+
596
+ result: Dict[str, Any] = {}
597
+
598
+ # Extract sizing mode
599
+ sizing = diagrams.get('sizing')
600
+ if sizing in ('consistent', 'fixed', 'auto'):
601
+ result['sizing'] = sizing
602
+
603
+ # Extract min_scale
604
+ min_scale = diagrams.get('min_scale')
605
+ if min_scale is not None:
606
+ try:
607
+ result['min_scale'] = float(min_scale)
608
+ except (TypeError, ValueError):
609
+ logger.warning(f"Invalid min_scale value: {min_scale}")
610
+
611
+ # Extract rotation mode
612
+ rotation = diagrams.get('rotation')
613
+ if rotation in ('warn', 'auto', 'none'):
614
+ result['rotation'] = rotation
615
+
616
+ # Extract page dimensions
617
+ for dim_key in ('page_width', 'page_height'):
618
+ dim_value = diagrams.get(dim_key)
619
+ if dim_value is not None:
620
+ try:
621
+ result[dim_key] = float(dim_value)
622
+ except (TypeError, ValueError):
623
+ logger.warning(f"Invalid {dim_key} value: {dim_value}")
624
+
625
+ # Extract tool-specific configurations
626
+ for tool in ('mermaid', 'plantuml', 'graphviz'):
627
+ tool_config = diagrams.get(tool)
628
+ if isinstance(tool_config, dict):
629
+ tool_result = {}
630
+ # Extract font_size
631
+ font_size = tool_config.get('font_size')
632
+ if font_size is not None:
633
+ try:
634
+ tool_result['font_size'] = int(font_size)
635
+ except (TypeError, ValueError):
636
+ logger.warning(f"Invalid font_size for {tool}: {font_size}")
637
+ # Extract other tool-specific options as-is
638
+ for key, value in tool_config.items():
639
+ if key != 'font_size':
640
+ tool_result[key] = value
641
+ if tool_result:
642
+ result[tool] = tool_result
643
+
644
+ return result