@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,1021 @@
1
+ """Logo replacement system module.
2
+
3
+ Provides functions for detecting and replacing logo placeholders in documents.
4
+ """
5
+ import logging
6
+ import re
7
+ import zipfile
8
+ import tempfile
9
+ import os
10
+ import shutil
11
+ import struct
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from typing import Any, Dict, List, Optional, Tuple
15
+ from xml.etree import ElementTree as ET
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ def get_image_dimensions(image_path: Path) -> Optional[Tuple[int, int]]:
21
+ """Get width and height of an image file.
22
+
23
+ Supports PNG, JPEG, and GIF formats.
24
+
25
+ Args:
26
+ image_path: Path to the image file.
27
+
28
+ Returns:
29
+ Tuple of (width, height) in pixels, or None if unable to determine.
30
+ """
31
+ if not image_path.exists():
32
+ return None
33
+
34
+ try:
35
+ with open(image_path, 'rb') as f:
36
+ header = f.read(32)
37
+
38
+ # PNG: signature + IHDR chunk
39
+ if header[:8] == b'\x89PNG\r\n\x1a\n':
40
+ width = struct.unpack('>I', header[16:20])[0]
41
+ height = struct.unpack('>I', header[20:24])[0]
42
+ return (width, height)
43
+
44
+ # JPEG
45
+ if header[:2] == b'\xff\xd8':
46
+ f.seek(0)
47
+ f.read(2) # Skip SOI marker
48
+ while True:
49
+ marker, = struct.unpack('>H', f.read(2))
50
+ if marker == 0xFFD9: # EOI
51
+ break
52
+ if marker == 0xFFDA: # Start of scan
53
+ break
54
+ length, = struct.unpack('>H', f.read(2))
55
+ if marker in (0xFFC0, 0xFFC1, 0xFFC2): # SOF markers
56
+ f.read(1) # precision
57
+ height, width = struct.unpack('>HH', f.read(4))
58
+ return (width, height)
59
+ f.seek(length - 2, 1)
60
+ return None
61
+
62
+ # GIF
63
+ if header[:6] in (b'GIF87a', b'GIF89a'):
64
+ width, height = struct.unpack('<HH', header[6:10])
65
+ return (width, height)
66
+
67
+ except Exception as e:
68
+ logger.debug(f"Could not read image dimensions from {image_path}: {e}")
69
+
70
+ return None
71
+
72
+ # Pattern for logo placeholder in alt text
73
+ LOGO_PLACEHOLDER_PATTERN = re.compile(r'\{\{logo:([^}]+)\}\}')
74
+
75
+
76
+ @dataclass
77
+ class LogoConfig:
78
+ """Configuration for a logo replacement.
79
+
80
+ Attributes:
81
+ name: The placeholder name (without {{logo:}}).
82
+ file: Path to the logo file.
83
+ width: Optional width for the logo.
84
+ height: Optional height for the logo.
85
+ """
86
+ name: str
87
+ file: Optional[Path] = None
88
+ width: Optional[int] = None
89
+ height: Optional[int] = None
90
+
91
+ @classmethod
92
+ def from_dict(cls, name: str, config: Any) -> 'LogoConfig':
93
+ """Create LogoConfig from a dictionary or string.
94
+
95
+ Args:
96
+ name: The logo placeholder name.
97
+ config: Either a path string or a dict with file, width, height.
98
+
99
+ Returns:
100
+ LogoConfig instance.
101
+ """
102
+ if isinstance(config, str):
103
+ return cls(name=name, file=Path(config))
104
+ elif isinstance(config, dict):
105
+ file_path = config.get('file')
106
+ return cls(
107
+ name=name,
108
+ file=Path(file_path) if file_path else None,
109
+ width=config.get('width'),
110
+ height=config.get('height'),
111
+ )
112
+ return cls(name=name)
113
+
114
+
115
+ def is_logo_placeholder(text: str) -> Optional[str]:
116
+ """Check if text contains a logo placeholder.
117
+
118
+ Args:
119
+ text: The text to check (alt text or caption).
120
+
121
+ Returns:
122
+ The logo name if a placeholder is found, None otherwise.
123
+ """
124
+ if not text:
125
+ return None
126
+ match = LOGO_PLACEHOLDER_PATTERN.search(text)
127
+ if match:
128
+ return match.group(1)
129
+ return None
130
+
131
+
132
+ def extract_logo_from_alt_or_caption(
133
+ alt_text: Optional[str],
134
+ caption: Optional[str]
135
+ ) -> tuple[Optional[str], bool]:
136
+ """Extract logo name from alt text or caption.
137
+
138
+ Checks alt text first, then caption. Returns whether the logo
139
+ was found in caption (to indicate caption should be removed).
140
+
141
+ Args:
142
+ alt_text: The image alt text.
143
+ caption: The image caption text.
144
+
145
+ Returns:
146
+ Tuple of (logo_name, found_in_caption).
147
+ logo_name is None if no placeholder found.
148
+ found_in_caption is True if logo was detected from caption.
149
+ """
150
+ # Check alt text first
151
+ logo_name = is_logo_placeholder(alt_text)
152
+ if logo_name:
153
+ return (logo_name, False)
154
+
155
+ # Check caption
156
+ logo_name = is_logo_placeholder(caption)
157
+ if logo_name:
158
+ return (logo_name, True)
159
+
160
+ return (None, False)
161
+
162
+
163
+ def remove_logo_placeholder_from_text(text: str) -> str:
164
+ """Remove logo placeholder pattern from text.
165
+
166
+ Args:
167
+ text: Text containing {{logo:name}} pattern.
168
+
169
+ Returns:
170
+ Text with logo placeholder removed and whitespace cleaned up.
171
+ """
172
+ if not text:
173
+ return text
174
+
175
+ # Remove the placeholder pattern
176
+ cleaned = LOGO_PLACEHOLDER_PATTERN.sub('', text)
177
+
178
+ # Clean up extra whitespace
179
+ cleaned = re.sub(r'\s+', ' ', cleaned).strip()
180
+
181
+ return cleaned
182
+
183
+
184
+ def parse_logos_frontmatter(frontmatter: Dict[str, Any]) -> Dict[str, LogoConfig]:
185
+ """Parse logos configuration from frontmatter.
186
+
187
+ Args:
188
+ frontmatter: Parsed frontmatter dictionary.
189
+
190
+ Returns:
191
+ Dictionary mapping logo names to LogoConfig.
192
+ """
193
+ logos_dict = frontmatter.get('logos', {})
194
+ if not isinstance(logos_dict, dict):
195
+ return {}
196
+
197
+ result = {}
198
+ for name, config in logos_dict.items():
199
+ result[name] = LogoConfig.from_dict(name, config)
200
+ return result
201
+
202
+
203
+ def extract_logos_from_markdown(markdown_content: str) -> Dict[str, LogoConfig]:
204
+ """Extract logo mappings from markdown image syntax.
205
+
206
+ Finds images with alt text in the format {{logo:name}} and extracts
207
+ the logo name and image path. This allows defining logos inline:
208
+
209
+ ![{{logo:company}}](images/logo.png)
210
+
211
+ Args:
212
+ markdown_content: The markdown content to parse.
213
+
214
+ Returns:
215
+ Dictionary mapping logo names to LogoConfig.
216
+ """
217
+ result = {}
218
+
219
+ # Pattern to match ![{{logo:name}}](path) or ![{{logo:name}}](path "title")
220
+ # Also handles spaces: ![ {{ logo:name }} ]( path )
221
+ pattern = r'!\[\s*\{\{\s*logo:([^}]+?)\s*\}\}\s*\]\(([^)\s]+)(?:\s+"[^"]*")?\)'
222
+
223
+ for match in re.finditer(pattern, markdown_content):
224
+ logo_name = match.group(1).strip()
225
+ image_path = match.group(2).strip()
226
+
227
+ if logo_name and image_path:
228
+ result[logo_name] = LogoConfig(
229
+ name=logo_name,
230
+ file=Path(image_path)
231
+ )
232
+ logger.debug(f"Extracted logo from markdown: {logo_name} -> {image_path}")
233
+
234
+ return result
235
+
236
+
237
+ def merge_logo_configs(
238
+ frontmatter_logos: Dict[str, LogoConfig],
239
+ markdown_logos: Dict[str, LogoConfig]
240
+ ) -> Dict[str, LogoConfig]:
241
+ """Merge logo configurations from frontmatter and markdown.
242
+
243
+ Frontmatter logos take precedence over markdown-extracted logos.
244
+
245
+ Args:
246
+ frontmatter_logos: Logos from frontmatter configuration.
247
+ markdown_logos: Logos extracted from markdown image syntax.
248
+
249
+ Returns:
250
+ Merged dictionary of logo configurations.
251
+ """
252
+ # Start with markdown logos
253
+ result = dict(markdown_logos)
254
+
255
+ # Frontmatter overrides markdown
256
+ result.update(frontmatter_logos)
257
+
258
+ return result
259
+
260
+
261
+ def resolve_logo_path(
262
+ logo_name: str,
263
+ frontmatter_logos: Dict[str, LogoConfig],
264
+ template_path: Optional[Path] = None,
265
+ source_path: Optional[Path] = None,
266
+ project_root: Optional[Path] = None
267
+ ) -> Optional[Path]:
268
+ """Resolve the file path for a logo.
269
+
270
+ Path resolution rules:
271
+ - Paths starting with '/' are relative to project_root
272
+ - Other paths are relative to the source document directory
273
+ - Absolute paths (e.g., /Users/...) are used as-is
274
+
275
+ Search order:
276
+ 1. Frontmatter logos configuration
277
+ 2. Template logos directory
278
+ 3. Source file's images directory
279
+
280
+ Args:
281
+ logo_name: The logo placeholder name.
282
+ frontmatter_logos: Logo configurations from frontmatter.
283
+ template_path: Path to the template directory.
284
+ source_path: Path to the source document.
285
+ project_root: Path to the project root directory.
286
+
287
+ Returns:
288
+ Resolved Path to the logo file, or None if not found.
289
+ """
290
+ # Check frontmatter configuration
291
+ if logo_name in frontmatter_logos:
292
+ config = frontmatter_logos[logo_name]
293
+ if config.file:
294
+ file_str = str(config.file)
295
+
296
+ # Check if it's a true absolute path (e.g., /Users/... or C:\...)
297
+ if config.file.is_absolute() and config.file.exists():
298
+ return config.file
299
+
300
+ # Path starting with '/' - relative to project root
301
+ if file_str.startswith('/') and project_root:
302
+ # Remove leading '/' and resolve from project root
303
+ rel_path = project_root / file_str.lstrip('/')
304
+ if rel_path.exists():
305
+ return rel_path
306
+
307
+ # Relative path - resolve from source document directory
308
+ if source_path:
309
+ rel_path = source_path.parent / config.file
310
+ if rel_path.exists():
311
+ return rel_path
312
+
313
+ # Common image extensions to try
314
+ extensions = ['.png', '.jpg', '.jpeg', '.svg', '.gif']
315
+
316
+ # Check template logos directory
317
+ if template_path:
318
+ logos_dir = template_path / 'logos'
319
+ if logos_dir.exists():
320
+ for ext in extensions:
321
+ logo_file = logos_dir / f"{logo_name}{ext}"
322
+ if logo_file.exists():
323
+ return logo_file
324
+
325
+ # Check source images directory
326
+ if source_path:
327
+ images_dir = source_path.parent / 'images'
328
+ if images_dir.exists():
329
+ for ext in extensions:
330
+ logo_file = images_dir / f"{logo_name}{ext}"
331
+ if logo_file.exists():
332
+ return logo_file
333
+
334
+ return None
335
+
336
+
337
+ def list_template_logos(template_path: Path) -> List[str]:
338
+ """List available logos in a template's logos directory.
339
+
340
+ Args:
341
+ template_path: Path to the template directory.
342
+
343
+ Returns:
344
+ List of logo file names (without extension).
345
+ """
346
+ logos_dir = template_path / 'logos'
347
+ if not logos_dir.exists():
348
+ return []
349
+
350
+ logos = []
351
+ extensions = {'.png', '.jpg', '.jpeg', '.svg', '.gif'}
352
+
353
+ for file in logos_dir.iterdir():
354
+ if file.suffix.lower() in extensions:
355
+ logos.append(file.stem)
356
+
357
+ return sorted(logos)
358
+
359
+
360
+ def extract_logos_to_frontmatter(placeholders: List[Dict[str, Any]], images_dir: Path) -> Dict[str, Any]:
361
+ """Generate logos frontmatter from detected placeholders.
362
+
363
+ Args:
364
+ placeholders: List of detected logo placeholder dictionaries.
365
+ images_dir: Directory where images are extracted.
366
+
367
+ Returns:
368
+ Dictionary suitable for frontmatter logos section.
369
+ """
370
+ logos = {}
371
+
372
+ for placeholder in placeholders:
373
+ name = placeholder.get('name')
374
+ if not name:
375
+ continue
376
+
377
+ # Check if logo file exists in images dir
378
+ extensions = ['.png', '.jpg', '.jpeg', '.svg', '.gif']
379
+ for ext in extensions:
380
+ logo_file = images_dir / f"{name}{ext}"
381
+ if logo_file.exists():
382
+ logos[name] = str(logo_file.relative_to(images_dir.parent))
383
+ break
384
+ else:
385
+ # Just record the placeholder name
386
+ logos[name] = f"images/{name}.png"
387
+
388
+ return logos
389
+
390
+
391
+ def _get_image_emu_dimensions(
392
+ doc_xml_path: Path,
393
+ rels_content: str,
394
+ target_filename: str
395
+ ) -> Optional[Tuple[int, int]]:
396
+ """Get image display dimensions from document XML in EMUs.
397
+
398
+ Args:
399
+ doc_xml_path: Path to document.xml file.
400
+ rels_content: Content of document.xml.rels for finding image references.
401
+ target_filename: Filename of the target image (e.g., 'image1.png').
402
+
403
+ Returns:
404
+ Tuple of (width, height) in EMUs, or None if not found.
405
+ """
406
+ if not doc_xml_path.exists():
407
+ return None
408
+
409
+ content = doc_xml_path.read_text(encoding='utf-8')
410
+
411
+ # Find the relationship ID for this image
412
+ rel_pattern = rf'<Relationship[^>]*Target="media/{re.escape(target_filename)}"[^>]*Id="([^"]+)"'
413
+ rel_match = re.search(rel_pattern, rels_content)
414
+ if not rel_match:
415
+ rel_pattern = rf'<Relationship[^>]*Id="([^"]+)"[^>]*Target="media/{re.escape(target_filename)}"'
416
+ rel_match = re.search(rel_pattern, rels_content)
417
+
418
+ if not rel_match:
419
+ return None
420
+
421
+ image_rid = rel_match.group(1)
422
+
423
+ # Find the drawing that contains this image and get wp:extent dimensions
424
+ drawing_pattern = rf'<w:drawing>((?:(?!</w:drawing>).)*r:embed="{image_rid}"(?:(?!</w:drawing>).)*)</w:drawing>'
425
+ drawing_match = re.search(drawing_pattern, content, re.DOTALL)
426
+
427
+ if not drawing_match:
428
+ return None
429
+
430
+ drawing_content = drawing_match.group(1)
431
+
432
+ # Extract wp:extent cx and cy
433
+ extent_pattern = r'<wp:extent\s+cx="(\d+)"\s+cy="(\d+)"'
434
+ extent_match = re.search(extent_pattern, drawing_content)
435
+
436
+ if extent_match:
437
+ return (int(extent_match.group(1)), int(extent_match.group(2)))
438
+
439
+ return None
440
+
441
+
442
+ def _update_image_dimensions_in_xml(
443
+ doc_xml_path: Path,
444
+ rels_content: str,
445
+ target_filename: str,
446
+ new_width: int,
447
+ new_height: int,
448
+ offset_x: int,
449
+ offset_y: int
450
+ ) -> bool:
451
+ """Update image dimensions and position in document XML.
452
+
453
+ Finds the drawing element that references the target image and updates:
454
+ - wp:extent cx/cy (display dimensions)
455
+ - a:ext cx/cy (image extent)
456
+ - wp:positionH/wp:positionV posOffset (if absolute positioning, adjust for centering)
457
+
458
+ Args:
459
+ doc_xml_path: Path to document.xml file.
460
+ rels_content: Content of document.xml.rels for finding image references.
461
+ target_filename: Filename of the target image (e.g., 'image1.png').
462
+ new_width: New width in EMUs.
463
+ new_height: New height in EMUs.
464
+ offset_x: X offset in EMUs to adjust position for centering.
465
+ offset_y: Y offset in EMUs to adjust position for centering.
466
+
467
+ Returns:
468
+ True if dimensions were updated, False otherwise.
469
+ """
470
+ if not doc_xml_path.exists():
471
+ return False
472
+
473
+ content = doc_xml_path.read_text(encoding='utf-8')
474
+
475
+ # Find the relationship ID for this image
476
+ # Pattern: Target="media/image1.png" ... Id="rId9"
477
+ rel_pattern = rf'<Relationship[^>]*Target="media/{re.escape(target_filename)}"[^>]*Id="([^"]+)"'
478
+ rel_match = re.search(rel_pattern, rels_content)
479
+ if not rel_match:
480
+ # Try alternate order
481
+ rel_pattern = rf'<Relationship[^>]*Id="([^"]+)"[^>]*Target="media/{re.escape(target_filename)}"'
482
+ rel_match = re.search(rel_pattern, rels_content)
483
+
484
+ if not rel_match:
485
+ logger.debug(f"Could not find relationship for image: {target_filename}")
486
+ return False
487
+
488
+ image_rid = rel_match.group(1)
489
+ logger.debug(f"Found image relationship {image_rid} for {target_filename}")
490
+
491
+ # Find the drawing that contains a:blip r:embed="image_rid"
492
+ # and update its dimensions
493
+ drawing_pattern = rf'(<w:drawing>)((?:(?!</w:drawing>).)*r:embed="{image_rid}"(?:(?!</w:drawing>).)*)(</w:drawing>)'
494
+ drawing_match = re.search(drawing_pattern, content, re.DOTALL)
495
+
496
+ if not drawing_match:
497
+ logger.debug(f"Could not find drawing for image {image_rid}")
498
+ return False
499
+
500
+ drawing_content = drawing_match.group(2)
501
+ modified = False
502
+
503
+ # Update wp:extent cx="..." cy="..."
504
+ extent_pattern = r'(<wp:extent\s+)cx="(\d+)"\s+cy="(\d+)"'
505
+ def replace_extent(m):
506
+ nonlocal modified
507
+ modified = True
508
+ return f'{m.group(1)}cx="{new_width}" cy="{new_height}"'
509
+
510
+ new_drawing_content = re.sub(extent_pattern, replace_extent, drawing_content)
511
+
512
+ # Update a:ext cx="..." cy="..." (inside a:xfrm)
513
+ aext_pattern = r'(<a:ext\s+)cx="(\d+)"\s+cy="(\d+)"'
514
+ new_drawing_content = re.sub(aext_pattern, replace_extent, new_drawing_content)
515
+
516
+ # If absolute positioning, adjust position to keep center aligned
517
+ if offset_x != 0 or offset_y != 0:
518
+ # Update horizontal position offset
519
+ def adjust_h_offset(m):
520
+ old_offset = int(m.group(2))
521
+ new_offset = old_offset + offset_x
522
+ return f'{m.group(1)}<wp:posOffset>{new_offset}</wp:posOffset>'
523
+
524
+ h_pattern = r'(<wp:positionH[^>]*>)\s*<wp:posOffset>(\d+)</wp:posOffset>'
525
+ new_drawing_content = re.sub(h_pattern, adjust_h_offset, new_drawing_content)
526
+
527
+ # Update vertical position offset
528
+ def adjust_v_offset(m):
529
+ old_offset = int(m.group(2))
530
+ new_offset = old_offset + offset_y
531
+ return f'{m.group(1)}<wp:posOffset>{new_offset}</wp:posOffset>'
532
+
533
+ v_pattern = r'(<wp:positionV[^>]*>)\s*<wp:posOffset>(\d+)</wp:posOffset>'
534
+ new_drawing_content = re.sub(v_pattern, adjust_v_offset, new_drawing_content)
535
+
536
+ if modified:
537
+ # Rebuild the drawing element
538
+ new_drawing = f'{drawing_match.group(1)}{new_drawing_content}{drawing_match.group(3)}'
539
+ new_content = content[:drawing_match.start()] + new_drawing + content[drawing_match.end():]
540
+ doc_xml_path.write_text(new_content, encoding='utf-8')
541
+ logger.debug(f"Updated dimensions for {target_filename}")
542
+ return True
543
+
544
+ return False
545
+
546
+
547
+ def _replace_fragmented_logo_placeholder(content: str, logo_name: str) -> tuple[str, bool]:
548
+ """Replace a {{logo:name}} pattern that may be fragmented across XML elements.
549
+
550
+ Word often splits text like {{logo:company}} into multiple <w:t> elements:
551
+ <w:t>{{</w:t><w:t>logo:company</w:t><w:t>}}</w:t>
552
+
553
+ This function finds such fragmented patterns and removes them.
554
+
555
+ Args:
556
+ content: XML content.
557
+ logo_name: Logo name (without {{logo:}}).
558
+
559
+ Returns:
560
+ Tuple of (modified content, whether replacement was made).
561
+ """
562
+ # First try simple replacement
563
+ simple_pattern = f'{{{{logo:{logo_name}}}}}'
564
+ if simple_pattern in content:
565
+ return content.replace(simple_pattern, ''), True
566
+
567
+ # Try with spaces
568
+ spaced_pattern = f'{{{{ logo:{logo_name} }}}}'
569
+ if spaced_pattern in content:
570
+ return content.replace(spaced_pattern, ''), True
571
+
572
+ # For fragmented patterns, find <w:t> elements that together contain the pattern
573
+ wt_pattern = r'(<w:t[^>]*>)([^<]*)(</w:t>)'
574
+
575
+ matches = list(re.finditer(wt_pattern, content))
576
+ if not matches:
577
+ return content, False
578
+
579
+ # Target patterns to look for
580
+ targets = [
581
+ f'{{{{logo:{logo_name}}}}}',
582
+ f'{{{{ logo:{logo_name} }}}}',
583
+ f'{{{{logo:{logo_name} }}}}',
584
+ f'{{{{ logo:{logo_name}}}}}',
585
+ ]
586
+
587
+ result = content
588
+ replaced = False
589
+
590
+ for i in range(len(matches)):
591
+ combined_text = ''
592
+ match_indices = []
593
+
594
+ for j in range(i, min(i + 15, len(matches))):
595
+ combined_text += matches[j].group(2)
596
+ match_indices.append(j)
597
+
598
+ # Check if we found any target pattern
599
+ found_target = None
600
+ for target in targets:
601
+ if target in combined_text:
602
+ found_target = target
603
+ break
604
+
605
+ if found_target:
606
+ # Found the pattern - replace with empty string
607
+ pattern_start = combined_text.find(found_target)
608
+ pattern_end = pattern_start + len(found_target)
609
+
610
+ # Calculate which elements contain parts of the pattern
611
+ char_pos = 0
612
+ elements_to_modify = []
613
+ for idx in match_indices:
614
+ elem_text = matches[idx].group(2)
615
+ elem_start = char_pos
616
+ elem_end = char_pos + len(elem_text)
617
+
618
+ if elem_end > pattern_start and elem_start < pattern_end:
619
+ elements_to_modify.append((idx, elem_start, elem_end))
620
+
621
+ char_pos = elem_end
622
+
623
+ if elements_to_modify:
624
+ # Build new content, clearing text from affected elements
625
+ new_content_parts = []
626
+ last_end = 0
627
+
628
+ for idx, elem_start, elem_end in elements_to_modify:
629
+ m = matches[idx]
630
+ new_content_parts.append(result[last_end:m.start()])
631
+
632
+ # Calculate what part of this element's text to keep
633
+ elem_text = m.group(2)
634
+ keep_before = ''
635
+ keep_after = ''
636
+
637
+ if elem_start < pattern_start:
638
+ keep_before = elem_text[:pattern_start - elem_start]
639
+ if elem_end > pattern_end:
640
+ keep_after = elem_text[pattern_end - elem_start:]
641
+
642
+ # Reconstruct the element with modified text
643
+ new_text = keep_before + keep_after
644
+ new_content_parts.append(f'{m.group(1)}{new_text}{m.group(3)}')
645
+ last_end = m.end()
646
+
647
+ new_content_parts.append(result[last_end:])
648
+ result = ''.join(new_content_parts)
649
+ replaced = True
650
+ break
651
+
652
+ if replaced:
653
+ break
654
+
655
+ return result, replaced
656
+
657
+
658
+ def _find_logo_image_and_replace_cover(
659
+ tmp_path: Path,
660
+ logo_name: str,
661
+ logos: Dict[str, LogoConfig],
662
+ source_path: Optional[Path] = None
663
+ ) -> bool:
664
+ """Find logo image and use it to replace template header/cover logo.
665
+
666
+ This function supports two modes:
667
+ 1. Logo defined via markdown image: ![{{logo:name}}](path)
668
+ - Finds the drawing with {{logo:name}} in alt text
669
+ - Uses that embedded image to replace header/cover logo
670
+ - Removes the markdown image paragraph from the body
671
+
672
+ 2. Logo defined only in frontmatter: logos: { name: "path" }
673
+ - Resolves the logo path from frontmatter config
674
+ - Uses that file directly to replace header/cover logo
675
+
676
+ Args:
677
+ tmp_path: Path to extracted DOCX directory.
678
+ logo_name: The logo name (e.g., 'company').
679
+ logos: Dictionary of logo configurations.
680
+ source_path: Path to the source markdown file.
681
+
682
+ Returns:
683
+ True if replacement was made, False otherwise.
684
+ """
685
+ doc_xml_path = tmp_path / 'word' / 'document.xml'
686
+ rels_path = tmp_path / 'word' / '_rels' / 'document.xml.rels'
687
+
688
+ if not doc_xml_path.exists() or not rels_path.exists():
689
+ return False
690
+
691
+ content = doc_xml_path.read_text(encoding='utf-8')
692
+ rels_content = rels_path.read_text(encoding='utf-8')
693
+
694
+ # Also load header files and their relationships (logos are often in headers)
695
+ header_contents = {}
696
+ header_rels = {}
697
+ for header_file in ['header1.xml', 'header2.xml', 'header3.xml']:
698
+ header_path = tmp_path / 'word' / header_file
699
+ header_rels_path = tmp_path / 'word' / '_rels' / f'{header_file}.rels'
700
+ if header_path.exists():
701
+ header_contents[header_file] = header_path.read_text(encoding='utf-8')
702
+ if header_rels_path.exists():
703
+ header_rels[header_file] = header_rels_path.read_text(encoding='utf-8')
704
+
705
+ # Try to find drawing with {{logo:name}} in the descr attribute of wp:docPr
706
+ # Pattern: <wp:docPr descr="{{logo:company}}" .../>
707
+ # The drawing contains this docPr and also has <a:blip r:embed="rIdX"/>
708
+
709
+ # Build patterns to match the logo placeholder in descr
710
+ logo_patterns = [
711
+ rf'descr="\{{\{{logo:{logo_name}\}}\}}"',
712
+ rf'descr="\{{\{{ logo:{logo_name} \}}\}}"',
713
+ rf"descr='\{{\{{logo:{logo_name}\}}\}}'",
714
+ ]
715
+
716
+ logo_drawing_match = None
717
+ for pattern in logo_patterns:
718
+ # Find the drawing containing this docPr
719
+ drawing_pattern = rf'<w:drawing>((?:(?!</w:drawing>).)*{pattern}(?:(?!</w:drawing>).)*)</w:drawing>'
720
+ logo_drawing_match = re.search(drawing_pattern, content, re.DOTALL)
721
+ if logo_drawing_match:
722
+ break
723
+
724
+ drawing_full = None
725
+ logo_image_path = None
726
+
727
+ if logo_drawing_match:
728
+ # Mode 1: Logo from markdown image in document
729
+ drawing_content = logo_drawing_match.group(1)
730
+ drawing_full = logo_drawing_match.group(0)
731
+
732
+ # Extract the image relationship ID from the drawing
733
+ blip_match = re.search(r'<a:blip[^>]*r:embed="([^"]+)"', drawing_content)
734
+ if blip_match:
735
+ logo_image_rid = blip_match.group(1)
736
+
737
+ # Find the image file path from relationships
738
+ rel_match = re.search(rf'<Relationship[^>]*Id="{logo_image_rid}"[^>]*Target="([^"]+)"', rels_content)
739
+ if rel_match:
740
+ logo_image_target = rel_match.group(1)
741
+ logo_image_path = tmp_path / 'word' / logo_image_target
742
+ if not logo_image_path.exists():
743
+ logo_image_path = None
744
+ logger.debug(f"Logo image file not found in DOCX: {logo_image_target}")
745
+
746
+ if not logo_image_path:
747
+ # Mode 2: Logo defined only in frontmatter - resolve from config
748
+ if logo_name in logos and logos[logo_name].file:
749
+ config = logos[logo_name]
750
+ logo_file = config.file
751
+
752
+ # Resolve path relative to source document
753
+ if source_path and not logo_file.is_absolute():
754
+ resolved_path = source_path.parent / logo_file
755
+ if resolved_path.exists():
756
+ logo_image_path = resolved_path
757
+ logger.debug(f"Using logo from frontmatter config: {logo_image_path}")
758
+ elif logo_file.is_absolute() and logo_file.exists():
759
+ logo_image_path = logo_file
760
+ logger.debug(f"Using absolute logo path: {logo_image_path}")
761
+
762
+ if not logo_image_path:
763
+ logger.debug(f"No logo image found for: {logo_name}")
764
+ return False
765
+
766
+ # Strategy: Find the template's placeholder image to replace
767
+ # The template marks logo placeholders in several ways:
768
+ # 1. Image with hyperlink containing {{logo:name}} or {{logo/name}} in URL
769
+ # 2. descr attribute with {{logo:name}}
770
+ # 3. Fallback: image1.* (first image in template)
771
+
772
+ target_image_path = None
773
+
774
+ # Method 1: Find hyperlink relationships with {{logo:name}} pattern
775
+ # URL-encoded pattern: %7B%7Blogo/company%7D%7D = {{logo/company}}
776
+ # Also support {{logo:company}} format
777
+ logo_hyperlink_patterns = [
778
+ # URL-encoded with slash: {{logo/name}}
779
+ rf'<Relationship[^>]*Target="[^"]*%7B%7Blogo[/]{logo_name}%7D%7D[^"]*"[^>]*Id="([^"]+)"',
780
+ rf'<Relationship[^>]*Id="([^"]+)"[^>]*Target="[^"]*%7B%7Blogo[/]{logo_name}%7D%7D[^"]*"',
781
+ # URL-encoded with colon: {{logo:name}}
782
+ rf'<Relationship[^>]*Target="[^"]*%7B%7Blogo%3A{logo_name}%7D%7D[^"]*"[^>]*Id="([^"]+)"',
783
+ rf'<Relationship[^>]*Id="([^"]+)"[^>]*Target="[^"]*%7B%7Blogo%3A{logo_name}%7D%7D[^"]*"',
784
+ # Non-encoded patterns (less common)
785
+ rf'<Relationship[^>]*Target="[^"]*\{{\{{logo[/:]{logo_name}\}}\}}[^"]*"[^>]*Id="([^"]+)"',
786
+ rf'<Relationship[^>]*Id="([^"]+)"[^>]*Target="[^"]*\{{\{{logo[/:]{logo_name}\}}\}}[^"]*"',
787
+ ]
788
+
789
+ hyperlink_rid = None
790
+ for pattern in logo_hyperlink_patterns:
791
+ match = re.search(pattern, rels_content, re.IGNORECASE)
792
+ if match:
793
+ hyperlink_rid = match.group(1)
794
+ logger.debug(f"Found logo hyperlink relationship: {hyperlink_rid}")
795
+ break
796
+
797
+ # Find the image that has this hyperlink (via a:hlinkClick reference)
798
+ if hyperlink_rid:
799
+ # Find drawing with a:hlinkClick r:id="hyperlink_rid"
800
+ hlink_pattern = rf'<w:drawing>((?:(?!</w:drawing>).)*a:hlinkClick[^>]*r:id="{hyperlink_rid}"(?:(?!</w:drawing>).)*)</w:drawing>'
801
+ hlink_drawing = re.search(hlink_pattern, content, re.DOTALL)
802
+
803
+ if hlink_drawing:
804
+ drawing_content = hlink_drawing.group(1)
805
+ # Get the image embed ID
806
+ blip_match = re.search(r'<a:blip[^>]*r:embed="([^"]+)"', drawing_content)
807
+ if blip_match:
808
+ image_rid = blip_match.group(1)
809
+ # Find the image file
810
+ img_rel = re.search(rf'<Relationship[^>]*Id="{image_rid}"[^>]*Target="([^"]+)"', rels_content)
811
+ if img_rel:
812
+ img_target = img_rel.group(1)
813
+ target_image_path = tmp_path / 'word' / img_target
814
+ if target_image_path.exists():
815
+ logger.debug(f"Found logo placeholder image via hyperlink: {target_image_path}")
816
+ else:
817
+ target_image_path = None
818
+
819
+ # Fallback: search for image with {{logo:name}} in descr attribute
820
+ if not target_image_path:
821
+ descr_patterns = [
822
+ rf'<w:drawing>((?:(?!</w:drawing>).)*descr="[^"]*\{{\{{logo:{logo_name}\}}\}}[^"]*"(?:(?!</w:drawing>).)*)</w:drawing>',
823
+ rf'<w:drawing>((?:(?!</w:drawing>).)*descr="[^"]*\{{\{{ logo:{logo_name} \}}\}}[^"]*"(?:(?!</w:drawing>).)*)</w:drawing>',
824
+ ]
825
+
826
+ for pattern in descr_patterns:
827
+ descr_drawing = re.search(pattern, content, re.DOTALL)
828
+ if descr_drawing:
829
+ drawing_content = descr_drawing.group(1)
830
+ blip_match = re.search(r'<a:blip[^>]*r:embed="([^"]+)"', drawing_content)
831
+ if blip_match:
832
+ image_rid = blip_match.group(1)
833
+ img_rel = re.search(rf'<Relationship[^>]*Id="{image_rid}"[^>]*Target="([^"]+)"', rels_content)
834
+ if img_rel:
835
+ img_target = img_rel.group(1)
836
+ target_image_path = tmp_path / 'word' / img_target
837
+ if target_image_path.exists():
838
+ logger.debug(f"Found logo placeholder image via descr: {target_image_path}")
839
+ break
840
+ else:
841
+ target_image_path = None
842
+
843
+ # Fallback: Look for image1.* which is typically the template logo
844
+ # This works because pandoc copies media files from reference-doc
845
+ if not target_image_path:
846
+ word_media = tmp_path / 'word' / 'media'
847
+ if word_media.exists():
848
+ # Look for image1 with various extensions (standard template logo location)
849
+ for ext in ['.png', '.jpeg', '.jpg', '.gif', '.svg']:
850
+ image1_path = word_media / f'image1{ext}'
851
+ if image1_path.exists():
852
+ target_image_path = image1_path
853
+ logger.debug(f"Found template logo at standard location: {target_image_path}")
854
+ break
855
+
856
+ if not target_image_path:
857
+ logger.debug(f"No logo placeholder found in template for: {logo_name}")
858
+ return False
859
+
860
+ # Replace target image with logo image
861
+ if logo_image_path.exists() and target_image_path and target_image_path.exists():
862
+ # Get new image dimensions for aspect ratio calculation
863
+ new_dims = get_image_dimensions(logo_image_path)
864
+
865
+ # Copy the new logo over the old one
866
+ shutil.copy2(logo_image_path, target_image_path)
867
+ logger.info(f"Replaced template logo placeholder with: {logo_name}")
868
+
869
+ # Adjust image dimensions in XML to preserve aspect ratio and center
870
+ if new_dims:
871
+ new_w, new_h = new_dims
872
+ new_aspect = new_w / new_h if new_h > 0 else 1
873
+
874
+ target_filename = target_image_path.name
875
+
876
+ # Get original bounding box dimensions from XML (in EMUs)
877
+ old_emu_dims = _get_image_emu_dimensions(doc_xml_path, rels_content, target_filename)
878
+
879
+ if old_emu_dims:
880
+ old_emu_w, old_emu_h = old_emu_dims
881
+
882
+ # Calculate new dimensions that fit within original bounds while preserving aspect ratio
883
+ # Try fitting by width first
884
+ fit_by_width_w = old_emu_w
885
+ fit_by_width_h = int(old_emu_w / new_aspect)
886
+
887
+ # Try fitting by height
888
+ fit_by_height_h = old_emu_h
889
+ fit_by_height_w = int(old_emu_h * new_aspect)
890
+
891
+ # Choose the one that fits within bounds
892
+ if fit_by_width_h <= old_emu_h:
893
+ # Fitting by width works
894
+ new_display_w = fit_by_width_w
895
+ new_display_h = fit_by_width_h
896
+ else:
897
+ # Must fit by height
898
+ new_display_w = fit_by_height_w
899
+ new_display_h = fit_by_height_h
900
+
901
+ # Calculate position offset to keep center aligned
902
+ # offset = (old_size - new_size) / 2
903
+ offset_x = (old_emu_w - new_display_w) // 2
904
+ offset_y = (old_emu_h - new_display_h) // 2
905
+
906
+ # Update dimensions in document.xml
907
+ _update_image_dimensions_in_xml(
908
+ doc_xml_path, rels_content, target_filename,
909
+ new_display_w, new_display_h, offset_x, offset_y
910
+ )
911
+
912
+ logger.debug(f"Adjusted logo: original bounds {old_emu_w}x{old_emu_h} EMUs, "
913
+ f"new size {new_display_w}x{new_display_h} EMUs, offset ({offset_x}, {offset_y})")
914
+
915
+ # Only remove paragraph if logo was from a markdown image (not frontmatter-only)
916
+ if drawing_full:
917
+ # Remove the paragraph containing the logo image from the body
918
+ # Find the paragraph containing the logo drawing
919
+ para_pattern = rf'<w:p[^>]*>(?:(?!</w:p>).)*{re.escape(drawing_full)}(?:(?!</w:p>).)*</w:p>'
920
+ new_content = re.sub(para_pattern, '', content, count=1, flags=re.DOTALL)
921
+
922
+ # Also remove the ImageCaption paragraph that Pandoc creates
923
+ # Pattern: <w:p>...<w:pStyle w:val="ImageCaption"/>...<w:t>{{logo:name}}</w:t>...</w:p>
924
+ caption_patterns = [
925
+ rf'<w:p[^>]*>(?:(?!</w:p>).)*<w:pStyle w:val="ImageCaption"/>(?:(?!</w:p>).)*\{{\{{logo:{logo_name}\}}\}}(?:(?!</w:p>).)*</w:p>',
926
+ rf'<w:p[^>]*>(?:(?!</w:p>).)*<w:pStyle w:val="Caption"/>(?:(?!</w:p>).)*\{{\{{logo:{logo_name}\}}\}}(?:(?!</w:p>).)*</w:p>',
927
+ ]
928
+ for cap_pattern in caption_patterns:
929
+ new_content = re.sub(cap_pattern, '', new_content, flags=re.DOTALL)
930
+
931
+ doc_xml_path.write_text(new_content, encoding='utf-8')
932
+
933
+ return True
934
+
935
+ return False
936
+
937
+
938
+ def replace_logo_placeholders_in_docx(
939
+ docx_path: Path,
940
+ logos: Dict[str, LogoConfig],
941
+ source_path: Optional[Path] = None,
942
+ template_path: Optional[Path] = None,
943
+ project_root: Optional[Path] = None
944
+ ) -> int:
945
+ """Replace {{logo:name}} placeholders in a DOCX with actual images.
946
+
947
+ This function:
948
+ 1. Finds images with {{logo:name}} captions (from markdown ![{{logo:name}}](path))
949
+ 2. Uses those images to replace the template's cover page logo
950
+ 3. Removes the {{logo:name}} caption text and the body image paragraph
951
+
952
+ Args:
953
+ docx_path: Path to the DOCX file to modify.
954
+ logos: Dictionary of logo configurations from frontmatter/markdown.
955
+ source_path: Path to the source markdown file.
956
+ template_path: Path to the template directory.
957
+ project_root: Path to the project root directory.
958
+
959
+ Returns:
960
+ Number of logos replaced.
961
+ """
962
+ if not logos:
963
+ return 0
964
+
965
+ replaced_count = 0
966
+
967
+ with tempfile.TemporaryDirectory() as tmpdir:
968
+ tmp_path = Path(tmpdir)
969
+
970
+ # Extract DOCX
971
+ with zipfile.ZipFile(docx_path, 'r') as zf:
972
+ zf.extractall(tmp_path)
973
+
974
+ # Process each logo - try to find image and replace cover page logo
975
+ for logo_name, config in logos.items():
976
+ if _find_logo_image_and_replace_cover(tmp_path, logo_name, logos, source_path):
977
+ replaced_count += 1
978
+ else:
979
+ # Fall back to just removing placeholder text
980
+ doc_xml_path = tmp_path / 'word' / 'document.xml'
981
+ if doc_xml_path.exists():
982
+ content = doc_xml_path.read_text(encoding='utf-8')
983
+
984
+ # Loop to handle multiple occurrences
985
+ max_iterations = 50
986
+ iteration = 0
987
+
988
+ while iteration < max_iterations:
989
+ iteration += 1
990
+ new_content, was_replaced = _replace_fragmented_logo_placeholder(content, logo_name)
991
+
992
+ if was_replaced:
993
+ content = new_content
994
+ replaced_count += 1
995
+ logger.info(f"Removed logo placeholder: {logo_name}")
996
+ else:
997
+ break
998
+
999
+ doc_xml_path.write_text(content, encoding='utf-8')
1000
+
1001
+ if f'logo:{logo_name}' in content:
1002
+ logger.warning(f"Logo placeholder pattern still present: {logo_name}")
1003
+
1004
+ # Repack DOCX - ensure [Content_Types].xml is first (Word requirement)
1005
+ with zipfile.ZipFile(docx_path, 'w', zipfile.ZIP_DEFLATED) as zf:
1006
+ # Write [Content_Types].xml first (required by OOXML spec)
1007
+ content_types = tmp_path / '[Content_Types].xml'
1008
+ if content_types.exists():
1009
+ zf.write(content_types, '[Content_Types].xml')
1010
+
1011
+ # Write remaining files in sorted order
1012
+ for root_dir, dirs, files in os.walk(tmp_path):
1013
+ dirs.sort() # Ensure consistent directory order
1014
+ for file in sorted(files):
1015
+ if file == '[Content_Types].xml':
1016
+ continue # Already written
1017
+ file_path = Path(root_dir) / file
1018
+ arcname = file_path.relative_to(tmp_path)
1019
+ zf.write(file_path, arcname)
1020
+
1021
+ return replaced_count