@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,273 @@
1
+ """PlantUML Docker server lifecycle management.
2
+
3
+ This module manages a Docker-based PlantUML server for rendering diagrams.
4
+ The server is started on-demand and can be stopped when no longer needed.
5
+ """
6
+ import atexit
7
+ import socket
8
+ import subprocess
9
+ import time
10
+ from typing import Optional
11
+ import urllib.request
12
+ import urllib.error
13
+
14
+
15
+ class PlantUMLServerError(Exception):
16
+ """Exception raised for PlantUML server errors."""
17
+ pass
18
+
19
+
20
+ def get_available_port() -> int:
21
+ """Get an available port for the PlantUML server.
22
+
23
+ Returns:
24
+ An available port number.
25
+ """
26
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
27
+ s.bind(('', 0))
28
+ s.listen(1)
29
+ port = s.getsockname()[1]
30
+ return port
31
+
32
+
33
+ def check_docker_available() -> bool:
34
+ """Check if Docker is available and running.
35
+
36
+ Returns:
37
+ True if Docker is available, False otherwise.
38
+ """
39
+ try:
40
+ result = subprocess.run(
41
+ ['docker', 'info'],
42
+ capture_output=True,
43
+ timeout=10
44
+ )
45
+ return result.returncode == 0
46
+ except (FileNotFoundError, subprocess.TimeoutExpired):
47
+ return False
48
+
49
+
50
+ class PlantUMLServer:
51
+ """Manages a Docker-based PlantUML server.
52
+
53
+ The server uses a fixed container name to prevent multiple instances.
54
+ Lifecycle management tracks whether this process started the container
55
+ to determine if it should be stopped on exit.
56
+ """
57
+
58
+ CONTAINER_NAME = "docconv-plantuml-server"
59
+ IMAGE_NAME = "plantuml/plantuml-server:latest"
60
+ HEALTH_CHECK_PATH = "/png/SoWkIImgAStDuNBAJrBGjLDmpCbCJbMm"
61
+ HEALTH_CHECK_TIMEOUT = 30 # seconds
62
+
63
+ def __init__(self):
64
+ """Initialize the PlantUML server manager."""
65
+ self._started_by_us = False
66
+ self._port: Optional[int] = None
67
+ self._atexit_registered = False
68
+
69
+ def is_container_running(self) -> bool:
70
+ """Check if the PlantUML container is currently running.
71
+
72
+ Returns:
73
+ True if container is running, False otherwise.
74
+ """
75
+ result = subprocess.run(
76
+ ['docker', 'ps', '--format', '{{.Names}}'],
77
+ capture_output=True,
78
+ text=True
79
+ )
80
+ return self.CONTAINER_NAME in result.stdout.split('\n')
81
+
82
+ def is_container_exists(self) -> bool:
83
+ """Check if the PlantUML container exists (running or stopped).
84
+
85
+ Returns:
86
+ True if container exists, False otherwise.
87
+ """
88
+ result = subprocess.run(
89
+ ['docker', 'ps', '-a', '--format', '{{.Names}}'],
90
+ capture_output=True,
91
+ text=True
92
+ )
93
+ return self.CONTAINER_NAME in result.stdout.split('\n')
94
+
95
+ def get_container_port(self) -> Optional[int]:
96
+ """Get the host port mapped to the container's 8080 port.
97
+
98
+ Returns:
99
+ The host port number, or None if container is not running.
100
+ """
101
+ result = subprocess.run(
102
+ ['docker', 'port', self.CONTAINER_NAME, '8080'],
103
+ capture_output=True,
104
+ text=True
105
+ )
106
+ if result.returncode != 0 or not result.stdout.strip():
107
+ return None
108
+
109
+ # Parse output like "0.0.0.0:54321" or "0.0.0.0:54321->8080/tcp"
110
+ port_str = result.stdout.strip().split(':')[-1]
111
+ # Handle case where output includes ->8080/tcp
112
+ port_str = port_str.split('->')[0]
113
+ try:
114
+ return int(port_str)
115
+ except ValueError:
116
+ return None
117
+
118
+ def _wait_for_healthy(self, timeout: int = None) -> bool:
119
+ """Wait for the PlantUML server to become healthy.
120
+
121
+ Args:
122
+ timeout: Maximum time to wait in seconds.
123
+
124
+ Returns:
125
+ True if server became healthy, False if timeout.
126
+ """
127
+ if timeout is None:
128
+ timeout = self.HEALTH_CHECK_TIMEOUT
129
+
130
+ port = self._port or self.get_container_port()
131
+ if not port:
132
+ return False
133
+
134
+ url = f"http://localhost:{port}{self.HEALTH_CHECK_PATH}"
135
+ start_time = time.time()
136
+
137
+ while time.time() - start_time < timeout:
138
+ try:
139
+ with urllib.request.urlopen(url, timeout=2) as response:
140
+ if response.status == 200:
141
+ return True
142
+ except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError):
143
+ pass
144
+ time.sleep(0.5)
145
+
146
+ return False
147
+
148
+ def _start_container(self) -> None:
149
+ """Start an existing stopped container."""
150
+ result = subprocess.run(
151
+ ['docker', 'start', self.CONTAINER_NAME],
152
+ capture_output=True,
153
+ text=True
154
+ )
155
+ if result.returncode != 0:
156
+ raise PlantUMLServerError(
157
+ f"Failed to start container: {result.stderr}"
158
+ )
159
+
160
+ def _create_container(self) -> None:
161
+ """Create and start a new container."""
162
+ self._port = get_available_port()
163
+ result = subprocess.run(
164
+ [
165
+ 'docker', 'run', '-d',
166
+ '--name', self.CONTAINER_NAME,
167
+ '-p', f'{self._port}:8080',
168
+ self.IMAGE_NAME
169
+ ],
170
+ capture_output=True,
171
+ text=True
172
+ )
173
+ if result.returncode != 0:
174
+ raise PlantUMLServerError(
175
+ f"Failed to create container: {result.stderr}"
176
+ )
177
+
178
+ def _register_atexit(self) -> None:
179
+ """Register atexit handler to stop container on Python exit."""
180
+ if not self._atexit_registered:
181
+ atexit.register(self.stop_if_started_by_us)
182
+ self._atexit_registered = True
183
+
184
+ def ensure_running(self) -> str:
185
+ """Ensure the PlantUML server is running.
186
+
187
+ If the container is already running, returns its URL.
188
+ If the container exists but is stopped, starts it.
189
+ If the container doesn't exist, creates and starts it.
190
+
191
+ Returns:
192
+ The base URL of the PlantUML server (e.g., "http://localhost:12345").
193
+
194
+ Raises:
195
+ PlantUMLServerError: If Docker is not available or server fails to start.
196
+ """
197
+ if not check_docker_available():
198
+ raise PlantUMLServerError(
199
+ "Docker is not available. Please install and start Docker."
200
+ )
201
+
202
+ # Check if already running
203
+ if self.is_container_running():
204
+ port = self.get_container_port()
205
+ if port:
206
+ self._port = port
207
+ return f"http://localhost:{port}"
208
+
209
+ # Start or create container
210
+ if self.is_container_exists():
211
+ self._start_container()
212
+ self._started_by_us = True
213
+ # Get the port after starting
214
+ self._port = self.get_container_port()
215
+ else:
216
+ self._create_container()
217
+ self._started_by_us = True
218
+
219
+ # Wait for healthy
220
+ if not self._wait_for_healthy():
221
+ raise PlantUMLServerError(
222
+ "PlantUML server failed to become healthy"
223
+ )
224
+
225
+ # Register cleanup
226
+ self._register_atexit()
227
+
228
+ return f"http://localhost:{self._port}"
229
+
230
+ def stop_if_started_by_us(self) -> None:
231
+ """Stop the container only if this process started it.
232
+
233
+ This allows external processes (like preHooks) to keep the
234
+ container running across multiple invocations.
235
+ """
236
+ if not self._started_by_us:
237
+ return
238
+
239
+ try:
240
+ subprocess.run(
241
+ ['docker', 'stop', self.CONTAINER_NAME],
242
+ capture_output=True,
243
+ timeout=10
244
+ )
245
+ except (subprocess.TimeoutExpired, Exception):
246
+ pass # Best effort cleanup
247
+
248
+ def get_base_url(self) -> Optional[str]:
249
+ """Get the base URL of the running server.
250
+
251
+ Returns:
252
+ The base URL, or None if server is not running.
253
+ """
254
+ port = self._port or self.get_container_port()
255
+ if port:
256
+ return f"http://localhost:{port}"
257
+ return None
258
+
259
+
260
+ # Global singleton instance
261
+ _server_instance: Optional[PlantUMLServer] = None
262
+
263
+
264
+ def get_server() -> PlantUMLServer:
265
+ """Get the global PlantUML server instance.
266
+
267
+ Returns:
268
+ The global PlantUMLServer instance.
269
+ """
270
+ global _server_instance
271
+ if _server_instance is None:
272
+ _server_instance = PlantUMLServer()
273
+ return _server_instance
@@ -0,0 +1,80 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "document-converter"
7
+ version = "0.6.0"
8
+ description = "Convert Markdown files with Mermaid diagrams to DOCX format with professional styling"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = {text = "MIT"}
12
+ keywords = ["markdown", "docx", "mermaid", "document-conversion", "documentation", "pandoc"]
13
+ authors = [
14
+ {name = "Test Automation Team", email = "team@example.com"}
15
+ ]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "Intended Audience :: End Users/Desktop",
20
+ "Topic :: Documentation",
21
+ "Topic :: Text Processing :: Markup",
22
+ "Topic :: Utilities",
23
+ "License :: OSI Approved :: MIT License",
24
+ "Programming Language :: Python :: 3",
25
+ "Programming Language :: Python :: 3.8",
26
+ "Programming Language :: Python :: 3.9",
27
+ "Programming Language :: Python :: 3.10",
28
+ "Programming Language :: Python :: 3.11",
29
+ "Programming Language :: Python :: 3.12",
30
+ "Operating System :: OS Independent",
31
+ ]
32
+
33
+ dependencies = [
34
+ "pypandoc>=1.11", # Markdown to DOCX conversion with better formatting
35
+ "python-docx>=1.0.0", # DOCX manipulation for templates
36
+ "Pillow>=10.0.0", # Image handling (for Mermaid diagrams)
37
+ ]
38
+
39
+ [project.optional-dependencies]
40
+ dev = [
41
+ "pytest>=7.0.0",
42
+ "pytest-cov>=4.0.0",
43
+ "build>=0.10.0",
44
+ "twine>=4.0.0",
45
+ ]
46
+ all = [
47
+ "pypandoc>=1.11",
48
+ "python-docx>=1.0.0",
49
+ "Pillow>=10.0.0",
50
+ ]
51
+
52
+ [project.urls]
53
+ Homepage = "https://github.com/yourusername/document-converter"
54
+ Documentation = "https://github.com/yourusername/document-converter/blob/main/README.md"
55
+ Repository = "https://github.com/yourusername/document-converter"
56
+ Issues = "https://github.com/yourusername/document-converter/issues"
57
+ Changelog = "https://github.com/yourusername/document-converter/blob/main/CHANGELOG.md"
58
+
59
+ [project.scripts]
60
+ document-converter = "document_converter.cli:main"
61
+
62
+ [tool.pytest.ini_options]
63
+ testpaths = ["tests"]
64
+ pythonpath = ["src"]
65
+ addopts = "-v --cov=document_converter --cov-report=term-missing"
66
+
67
+ [tool.hatch.version]
68
+ path = "src/document_converter/__init__.py"
69
+
70
+ [tool.hatch.build.targets.wheel]
71
+ packages = ["src/document_converter"]
72
+
73
+ [tool.hatch.build.targets.sdist]
74
+ include = [
75
+ "/src",
76
+ "/tests",
77
+ "/README.md",
78
+ "/LICENSE",
79
+ "/CHANGELOG.md",
80
+ ]
@@ -0,0 +1,312 @@
1
+ """Round-trip editing module for DOCX-Markdown synchronization."""
2
+ from pathlib import Path
3
+ from typing import Dict, List, Optional, Tuple, Any
4
+ from dataclasses import dataclass
5
+ from difflib import SequenceMatcher
6
+ import shutil
7
+
8
+ from docx import Document
9
+ from docx.oxml.ns import qn
10
+
11
+ from .meta_mapper import load_metadata, find_metadata_path
12
+ from .docx_reader import ExtractionResult
13
+
14
+
15
+ @dataclass
16
+ class ChangeInfo:
17
+ """Information about a detected change."""
18
+ mapping_id: str
19
+ change_type: str # 'modified', 'deleted', 'added'
20
+ old_content: str
21
+ new_content: str
22
+ line_start: int
23
+ line_end: int
24
+ docx_path: str
25
+
26
+
27
+ @dataclass
28
+ class MergeResult:
29
+ """Result of a merge operation."""
30
+ success: bool
31
+ output_path: Path
32
+ changes_applied: List[ChangeInfo]
33
+ warnings: List[str]
34
+ preserved_count: int
35
+
36
+
37
+ def detect_changes(
38
+ original_md: str,
39
+ edited_md: str,
40
+ metadata: Dict[str, Any]
41
+ ) -> List[ChangeInfo]:
42
+ """Detect changes between original and edited Markdown.
43
+
44
+ Args:
45
+ original_md: Original Markdown content.
46
+ edited_md: Edited Markdown content.
47
+ metadata: Loaded metadata with mappings.
48
+
49
+ Returns:
50
+ List of ChangeInfo objects describing the changes.
51
+ """
52
+ changes = []
53
+
54
+ original_lines = original_md.split('\n')
55
+ edited_lines = edited_md.split('\n')
56
+
57
+ # Use SequenceMatcher to find differences
58
+ matcher = SequenceMatcher(None, original_lines, edited_lines)
59
+
60
+ # Track which mappings are affected
61
+ for mapping in metadata.get('mappings', []):
62
+ start = mapping.get('md_start', 1) - 1 # Convert to 0-indexed
63
+ end = mapping.get('md_end', 1) - 1
64
+
65
+ if start < 0:
66
+ continue
67
+
68
+ # Get original content for this mapping
69
+ if end < len(original_lines):
70
+ original_content = '\n'.join(original_lines[start:end + 1])
71
+ else:
72
+ original_content = '\n'.join(original_lines[start:])
73
+
74
+ # Check if this range was modified
75
+ # Find corresponding range in edited content
76
+ modified = False
77
+ new_content = original_content
78
+
79
+ for tag, i1, i2, j1, j2 in matcher.get_opcodes():
80
+ if tag == 'equal':
81
+ continue
82
+
83
+ # Check if this operation affects our range
84
+ if (i1 <= start <= i2) or (i1 <= end <= i2) or (start <= i1 and end >= i2):
85
+ modified = True
86
+
87
+ # Try to find new content
88
+ if tag == 'replace':
89
+ # Content was modified
90
+ if j1 < len(edited_lines) and j2 <= len(edited_lines):
91
+ new_content = '\n'.join(edited_lines[j1:j2])
92
+ elif tag == 'delete':
93
+ # Content was deleted
94
+ new_content = ''
95
+ elif tag == 'insert':
96
+ # New content was added
97
+ if j1 < len(edited_lines) and j2 <= len(edited_lines):
98
+ new_content = '\n'.join(edited_lines[j1:j2])
99
+
100
+ break
101
+
102
+ if modified:
103
+ change_type = 'deleted' if not new_content else 'modified'
104
+ changes.append(ChangeInfo(
105
+ mapping_id=mapping.get('id', ''),
106
+ change_type=change_type,
107
+ old_content=original_content,
108
+ new_content=new_content,
109
+ line_start=start + 1,
110
+ line_end=end + 1,
111
+ docx_path=mapping.get('docx_path', '')
112
+ ))
113
+
114
+ return changes
115
+
116
+
117
+ def update_paragraph_content(doc: Document, docx_path: str, new_content: str) -> bool:
118
+ """Update a paragraph's content in the document.
119
+
120
+ Args:
121
+ doc: The document to modify.
122
+ docx_path: XPath-like path to the paragraph.
123
+ new_content: New content for the paragraph.
124
+
125
+ Returns:
126
+ True if update was successful, False otherwise.
127
+ """
128
+ # Parse the docx_path to find the paragraph
129
+ # Expected format: /w:body/w:p[N]
130
+ import re
131
+ match = re.match(r'/w:body/w:p\[(\d+)\]', docx_path)
132
+ if not match:
133
+ return False
134
+
135
+ para_index = int(match.group(1)) - 1 # Convert to 0-indexed
136
+
137
+ if para_index < 0 or para_index >= len(doc.paragraphs):
138
+ return False
139
+
140
+ para = doc.paragraphs[para_index]
141
+
142
+ # Clear existing content
143
+ for run in para.runs:
144
+ run.text = ''
145
+
146
+ # Add new content
147
+ if para.runs:
148
+ para.runs[0].text = new_content
149
+ else:
150
+ para.add_run(new_content)
151
+
152
+ return True
153
+
154
+
155
+ def restore_preserved_elements(
156
+ doc: Document,
157
+ original_doc: Document,
158
+ preserved: List[Dict[str, Any]]
159
+ ) -> int:
160
+ """Restore preserved elements from original document.
161
+
162
+ Args:
163
+ doc: The document being updated.
164
+ original_doc: The original document.
165
+ preserved: List of preserved element information.
166
+
167
+ Returns:
168
+ Number of elements restored.
169
+ """
170
+ restored = 0
171
+
172
+ # For now, this is a placeholder
173
+ # Full implementation would copy XML elements from original_doc to doc
174
+ # based on the preserved element paths
175
+
176
+ # Charts and complex objects require copying the relationship
177
+ # and the XML element, which is complex with python-docx
178
+
179
+ return restored
180
+
181
+
182
+ def merge_document(
183
+ original_docx: Path,
184
+ edited_md: Path,
185
+ output_path: Path,
186
+ meta_path: Optional[Path] = None
187
+ ) -> MergeResult:
188
+ """Merge edited Markdown back into the original DOCX.
189
+
190
+ Args:
191
+ original_docx: Path to the original DOCX file.
192
+ edited_md: Path to the edited Markdown file.
193
+ output_path: Path for the output DOCX file.
194
+ meta_path: Path to the metadata file (auto-detected if None).
195
+
196
+ Returns:
197
+ MergeResult with merge details.
198
+ """
199
+ original_docx = Path(original_docx)
200
+ edited_md = Path(edited_md)
201
+ output_path = Path(output_path)
202
+
203
+ warnings = []
204
+
205
+ # Validate inputs
206
+ if not original_docx.exists():
207
+ raise FileNotFoundError(f"Original DOCX not found: {original_docx}")
208
+ if not edited_md.exists():
209
+ raise FileNotFoundError(f"Edited Markdown not found: {edited_md}")
210
+
211
+ # Find metadata file
212
+ if meta_path is None:
213
+ meta_path = find_metadata_path(edited_md)
214
+ if meta_path is None:
215
+ # Try to find it based on markdown filename
216
+ meta_path = edited_md.parent / f"{edited_md.stem}_meta.xml"
217
+
218
+ if meta_path is None or not meta_path.exists():
219
+ raise FileNotFoundError(
220
+ f"Metadata file not found. Expected: {edited_md.stem}_meta.xml"
221
+ )
222
+
223
+ # Load metadata
224
+ metadata = load_metadata(meta_path)
225
+
226
+ # Read original markdown (if available) and edited markdown
227
+ original_md_path = edited_md # Assume same path for original
228
+ if 'extracted' in metadata:
229
+ original_md_path = edited_md.parent / metadata['extracted']
230
+
231
+ # Read the edited markdown
232
+ edited_content = edited_md.read_text(encoding='utf-8')
233
+
234
+ # For comparison, we need the original markdown
235
+ # This should ideally be stored or reconstructed
236
+ # For now, we'll do a simplified approach
237
+ original_content = edited_content # Placeholder
238
+
239
+ # Detect changes
240
+ changes = detect_changes(original_content, edited_content, metadata)
241
+
242
+ if not changes:
243
+ # No changes detected, just copy the original
244
+ shutil.copy2(original_docx, output_path)
245
+ return MergeResult(
246
+ success=True,
247
+ output_path=output_path,
248
+ changes_applied=[],
249
+ warnings=["No changes detected, copied original document."],
250
+ preserved_count=0
251
+ )
252
+
253
+ # Copy original DOCX to output
254
+ shutil.copy2(original_docx, output_path)
255
+
256
+ # Open the copy and apply changes
257
+ doc = Document(output_path)
258
+ original_doc = Document(original_docx)
259
+
260
+ changes_applied = []
261
+ for change in changes:
262
+ if change.change_type == 'deleted':
263
+ warnings.append(f"Skipping deleted content at {change.docx_path}")
264
+ continue
265
+
266
+ success = update_paragraph_content(doc, change.docx_path, change.new_content)
267
+ if success:
268
+ changes_applied.append(change)
269
+ else:
270
+ warnings.append(f"Failed to update {change.docx_path}")
271
+
272
+ # Restore preserved elements
273
+ preserved = metadata.get('preserved', [])
274
+ preserved_count = restore_preserved_elements(doc, original_doc, preserved)
275
+
276
+ # Save the merged document
277
+ doc.save(output_path)
278
+
279
+ return MergeResult(
280
+ success=True,
281
+ output_path=output_path,
282
+ changes_applied=changes_applied,
283
+ warnings=warnings,
284
+ preserved_count=preserved_count
285
+ )
286
+
287
+
288
+ def merge_md_to_docx(
289
+ original_docx: Path,
290
+ edited_md: Path,
291
+ output_path: Path,
292
+ meta_path: Optional[Path] = None
293
+ ) -> MergeResult:
294
+ """Public API for merging edited Markdown back into DOCX.
295
+
296
+ This is the main entry point for round-trip editing.
297
+
298
+ Args:
299
+ original_docx: Path to the original DOCX file.
300
+ edited_md: Path to the edited Markdown file.
301
+ output_path: Path for the output DOCX file.
302
+ meta_path: Path to the metadata file (auto-detected if None).
303
+
304
+ Returns:
305
+ MergeResult with merge details.
306
+ """
307
+ return merge_document(
308
+ original_docx=Path(original_docx),
309
+ edited_md=Path(edited_md),
310
+ output_path=Path(output_path),
311
+ meta_path=Path(meta_path) if meta_path else None
312
+ )