@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.
- package/.pi/skills/document-converter/SKILL.md +79 -0
- package/README.md +106 -0
- package/engine/.dockerignore +4 -0
- package/engine/Dockerfile +75 -0
- package/engine/IMAGE_VERSION +1 -0
- package/engine/README.md +65 -0
- package/engine/VENDOR.md +40 -0
- package/engine/build-image.sh +29 -0
- package/engine/document_converter/LICENSE +21 -0
- package/engine/document_converter/__init__.py +365 -0
- package/engine/document_converter/__main__.py +5 -0
- package/engine/document_converter/asciidoc_converter.py +534 -0
- package/engine/document_converter/cli.py +751 -0
- package/engine/document_converter/code_renderer.py +356 -0
- package/engine/document_converter/converter.py +928 -0
- package/engine/document_converter/cover_page.py +448 -0
- package/engine/document_converter/diagram_resizer.py +311 -0
- package/engine/document_converter/diagram_sizing.py +357 -0
- package/engine/document_converter/docx_reader.py +627 -0
- package/engine/document_converter/field_updater.py +277 -0
- package/engine/document_converter/font_manager.py +850 -0
- package/engine/document_converter/frontmatter_parser.py +644 -0
- package/engine/document_converter/graphviz_renderer.py +354 -0
- package/engine/document_converter/image_extractor.py +281 -0
- package/engine/document_converter/image_style.py +237 -0
- package/engine/document_converter/logo_manager.py +1021 -0
- package/engine/document_converter/manifest_manager.py +288 -0
- package/engine/document_converter/mermaid_renderer.py +371 -0
- package/engine/document_converter/meta_mapper.py +398 -0
- package/engine/document_converter/pandoc_styles.py +222 -0
- package/engine/document_converter/pdf_converter.py +735 -0
- package/engine/document_converter/pdf_server.py +283 -0
- package/engine/document_converter/plantuml_renderer.py +460 -0
- package/engine/document_converter/plantuml_server.py +273 -0
- package/engine/document_converter/pyproject.toml +80 -0
- package/engine/document_converter/round_trip.py +312 -0
- package/engine/document_converter/spacing_applier.py +332 -0
- package/engine/document_converter/spacing_config.py +323 -0
- package/engine/document_converter/style_extractor.py +420 -0
- package/engine/document_converter/svg_embedder.py +294 -0
- package/engine/document_converter/system_variables.py +158 -0
- package/engine/document_converter/table_formatter.py +450 -0
- package/engine/document_converter/template_extractor.py +1334 -0
- package/engine/document_converter/template_manager.py +427 -0
- package/engine/document_converter/textbox_extractor.py +551 -0
- package/engine/document_converter/toc_generator.py +559 -0
- package/engine/document_converter/toc_style.py +290 -0
- package/engine/document_converter/tree_renderer.py +328 -0
- package/engine/document_converter/utils.py +134 -0
- package/engine/document_converter/variable_manager.py +394 -0
- package/engine/engine_cli.py +371 -0
- package/engine/frontmatter_filler/doc-meta.sample.yaml +106 -0
- package/engine/frontmatter_filler/fill.py +517 -0
- package/engine/markdown_table_profiler/profile.py +442 -0
- package/engine/nano-banana-styles.yaml +59 -0
- package/engine/tests/test_styled_diagrams.py +109 -0
- package/package.json +32 -0
- package/src/__tests__/engine.test.ts +72 -0
- package/src/__tests__/facade.test.ts +120 -0
- package/src/__tests__/integration.test.ts +101 -0
- package/src/__tests__/ocr.test.ts +34 -0
- package/src/__tests__/provenance.test.ts +89 -0
- package/src/__tests__/routing.test.ts +40 -0
- package/src/engine.ts +187 -0
- package/src/errors.ts +43 -0
- package/src/index.ts +179 -0
- package/src/ocr.ts +43 -0
- package/src/provenance.ts +79 -0
- package/src/routing.ts +49 -0
- package/src/schema.json +69 -0
- package/src/schema.ts +107 -0
- package/src/types.ts +90 -0
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
"""Metadata mapping module for bidirectional DOCX-Markdown synchronization."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Dict, List, Optional, Any, TYPE_CHECKING
|
|
4
|
+
from datetime import datetime, timezone
|
|
5
|
+
from xml.etree import ElementTree as ET
|
|
6
|
+
from xml.dom import minidom
|
|
7
|
+
|
|
8
|
+
if TYPE_CHECKING:
|
|
9
|
+
from .docx_reader import ExtractionResult, ExtractedElement
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
# XML namespace for metadata
|
|
13
|
+
META_NS = "http://document-converter/meta/1.0"
|
|
14
|
+
META_VERSION = "1.0"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def create_mapping(
|
|
18
|
+
elements: List['ExtractedElement'],
|
|
19
|
+
preserved: List[Dict[str, Any]],
|
|
20
|
+
images: List[Dict[str, Any]]
|
|
21
|
+
) -> ET.Element:
|
|
22
|
+
"""Create XML mapping structure from extracted elements.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
elements: List of extracted elements with line mappings.
|
|
26
|
+
preserved: List of preserved element information.
|
|
27
|
+
images: List of image information.
|
|
28
|
+
|
|
29
|
+
Returns:
|
|
30
|
+
XML Element containing the mapping structure.
|
|
31
|
+
"""
|
|
32
|
+
mappings = ET.Element('mappings')
|
|
33
|
+
|
|
34
|
+
for i, element in enumerate(elements):
|
|
35
|
+
mapping = ET.SubElement(mappings, 'mapping')
|
|
36
|
+
mapping.set('id', f"m{i + 1}")
|
|
37
|
+
|
|
38
|
+
# DOCX path
|
|
39
|
+
docx_path = ET.SubElement(mapping, 'docx-path')
|
|
40
|
+
docx_path.text = element.docx_path
|
|
41
|
+
|
|
42
|
+
# Markdown line range
|
|
43
|
+
md_range = ET.SubElement(mapping, 'md-range')
|
|
44
|
+
md_range.set('start', str(element.line_start))
|
|
45
|
+
md_range.set('end', str(element.line_end))
|
|
46
|
+
|
|
47
|
+
# Element type
|
|
48
|
+
elem_type = ET.SubElement(mapping, 'type')
|
|
49
|
+
elem_type.text = element.type
|
|
50
|
+
|
|
51
|
+
# Level (for headings and lists)
|
|
52
|
+
if element.level > 0:
|
|
53
|
+
level = ET.SubElement(mapping, 'level')
|
|
54
|
+
level.text = str(element.level)
|
|
55
|
+
|
|
56
|
+
# Style name
|
|
57
|
+
if element.style_name:
|
|
58
|
+
style = ET.SubElement(mapping, 'style')
|
|
59
|
+
style.text = element.style_name
|
|
60
|
+
|
|
61
|
+
# Additional metadata
|
|
62
|
+
if element.metadata:
|
|
63
|
+
meta = ET.SubElement(mapping, 'metadata')
|
|
64
|
+
for key, value in element.metadata.items():
|
|
65
|
+
if value is not None:
|
|
66
|
+
meta_item = ET.SubElement(meta, key.replace('_', '-'))
|
|
67
|
+
meta_item.text = str(value)
|
|
68
|
+
|
|
69
|
+
return mappings
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def create_preserved_section(
|
|
73
|
+
preserved: List[Dict[str, Any]],
|
|
74
|
+
images: List[Dict[str, Any]]
|
|
75
|
+
) -> ET.Element:
|
|
76
|
+
"""Create XML section for preserved elements.
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
preserved: List of preserved element information (charts, etc).
|
|
80
|
+
images: List of image information.
|
|
81
|
+
|
|
82
|
+
Returns:
|
|
83
|
+
XML Element containing preserved element references.
|
|
84
|
+
"""
|
|
85
|
+
section = ET.Element('preserved')
|
|
86
|
+
|
|
87
|
+
# Add preserved elements (charts, shapes, etc.)
|
|
88
|
+
for i, elem in enumerate(preserved):
|
|
89
|
+
element = ET.SubElement(section, 'element')
|
|
90
|
+
element.set('id', f"preserved_{i + 1}")
|
|
91
|
+
element.set('type', elem.get('type', 'unknown'))
|
|
92
|
+
|
|
93
|
+
if 'ref_id' in elem:
|
|
94
|
+
element.set('ref', elem['ref_id'])
|
|
95
|
+
|
|
96
|
+
docx_path = ET.SubElement(element, 'docx-path')
|
|
97
|
+
docx_path.text = elem.get('docx_path', '')
|
|
98
|
+
|
|
99
|
+
# Add image references
|
|
100
|
+
for i, img in enumerate(images):
|
|
101
|
+
element = ET.SubElement(section, 'element')
|
|
102
|
+
element.set('id', f"img_{i + 1}")
|
|
103
|
+
element.set('type', 'image')
|
|
104
|
+
|
|
105
|
+
if 'embed_id' in img:
|
|
106
|
+
element.set('ref', img['embed_id'])
|
|
107
|
+
|
|
108
|
+
docx_path = ET.SubElement(element, 'docx-path')
|
|
109
|
+
docx_path.text = img.get('docx_path', '')
|
|
110
|
+
|
|
111
|
+
if 'extracted_path' in img:
|
|
112
|
+
extracted = ET.SubElement(element, 'extracted-path')
|
|
113
|
+
extracted.text = img['extracted_path']
|
|
114
|
+
|
|
115
|
+
return section
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def prettify_xml(elem: ET.Element) -> str:
|
|
119
|
+
"""Return a pretty-printed XML string.
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
elem: XML Element to format.
|
|
123
|
+
|
|
124
|
+
Returns:
|
|
125
|
+
Formatted XML string.
|
|
126
|
+
"""
|
|
127
|
+
rough_string = ET.tostring(elem, encoding='unicode')
|
|
128
|
+
reparsed = minidom.parseString(rough_string)
|
|
129
|
+
return reparsed.toprettyxml(indent=" ")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def save_metadata(
|
|
133
|
+
result: 'ExtractionResult',
|
|
134
|
+
source_docx: Path,
|
|
135
|
+
output_md: Path,
|
|
136
|
+
meta_path: Path
|
|
137
|
+
) -> None:
|
|
138
|
+
"""Save extraction metadata to an XML file.
|
|
139
|
+
|
|
140
|
+
Args:
|
|
141
|
+
result: The extraction result containing elements and mappings.
|
|
142
|
+
source_docx: Path to the source DOCX file.
|
|
143
|
+
output_md: Path to the output Markdown file.
|
|
144
|
+
meta_path: Path for the metadata XML file.
|
|
145
|
+
"""
|
|
146
|
+
# Create root element
|
|
147
|
+
root = ET.Element('docmeta')
|
|
148
|
+
root.set('version', META_VERSION)
|
|
149
|
+
# Note: We don't set xmlns to simplify parsing with ElementTree
|
|
150
|
+
|
|
151
|
+
# Source file info
|
|
152
|
+
source = ET.SubElement(root, 'source')
|
|
153
|
+
source.text = source_docx.name
|
|
154
|
+
|
|
155
|
+
# Extracted file info
|
|
156
|
+
extracted = ET.SubElement(root, 'extracted')
|
|
157
|
+
extracted.text = output_md.name
|
|
158
|
+
|
|
159
|
+
# Timestamp
|
|
160
|
+
timestamp = ET.SubElement(root, 'timestamp')
|
|
161
|
+
timestamp.text = datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
|
|
162
|
+
|
|
163
|
+
# Add mappings
|
|
164
|
+
mappings = create_mapping(
|
|
165
|
+
result.elements,
|
|
166
|
+
result.preserved_elements,
|
|
167
|
+
result.images
|
|
168
|
+
)
|
|
169
|
+
root.append(mappings)
|
|
170
|
+
|
|
171
|
+
# Add preserved elements section
|
|
172
|
+
preserved = create_preserved_section(
|
|
173
|
+
result.preserved_elements,
|
|
174
|
+
result.images
|
|
175
|
+
)
|
|
176
|
+
root.append(preserved)
|
|
177
|
+
|
|
178
|
+
# Write to file
|
|
179
|
+
meta_path.parent.mkdir(parents=True, exist_ok=True)
|
|
180
|
+
xml_string = prettify_xml(root)
|
|
181
|
+
meta_path.write_text(xml_string, encoding='utf-8')
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def load_metadata(meta_path: Path) -> Dict[str, Any]:
|
|
185
|
+
"""Load metadata from an XML file.
|
|
186
|
+
|
|
187
|
+
Args:
|
|
188
|
+
meta_path: Path to the metadata XML file.
|
|
189
|
+
|
|
190
|
+
Returns:
|
|
191
|
+
Dictionary containing parsed metadata.
|
|
192
|
+
"""
|
|
193
|
+
if not meta_path.exists():
|
|
194
|
+
raise FileNotFoundError(f"Metadata file not found: {meta_path}")
|
|
195
|
+
|
|
196
|
+
tree = ET.parse(meta_path)
|
|
197
|
+
root = tree.getroot()
|
|
198
|
+
|
|
199
|
+
metadata = {
|
|
200
|
+
'version': root.get('version', '1.0'),
|
|
201
|
+
'source': '',
|
|
202
|
+
'extracted': '',
|
|
203
|
+
'timestamp': '',
|
|
204
|
+
'mappings': [],
|
|
205
|
+
'preserved': []
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
# Parse source and extracted file names
|
|
209
|
+
source_elem = root.find('source')
|
|
210
|
+
if source_elem is not None:
|
|
211
|
+
metadata['source'] = source_elem.text or ''
|
|
212
|
+
|
|
213
|
+
extracted_elem = root.find('extracted')
|
|
214
|
+
if extracted_elem is not None:
|
|
215
|
+
metadata['extracted'] = extracted_elem.text or ''
|
|
216
|
+
|
|
217
|
+
timestamp_elem = root.find('timestamp')
|
|
218
|
+
if timestamp_elem is not None:
|
|
219
|
+
metadata['timestamp'] = timestamp_elem.text or ''
|
|
220
|
+
|
|
221
|
+
# Parse mappings
|
|
222
|
+
mappings_elem = root.find('mappings')
|
|
223
|
+
if mappings_elem is not None:
|
|
224
|
+
for mapping in mappings_elem.findall('mapping'):
|
|
225
|
+
mapping_data = {
|
|
226
|
+
'id': mapping.get('id', ''),
|
|
227
|
+
'docx_path': '',
|
|
228
|
+
'md_start': 0,
|
|
229
|
+
'md_end': 0,
|
|
230
|
+
'type': '',
|
|
231
|
+
'level': 0,
|
|
232
|
+
'style': '',
|
|
233
|
+
'metadata': {}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
docx_path = mapping.find('docx-path')
|
|
237
|
+
if docx_path is not None:
|
|
238
|
+
mapping_data['docx_path'] = docx_path.text or ''
|
|
239
|
+
|
|
240
|
+
md_range = mapping.find('md-range')
|
|
241
|
+
if md_range is not None:
|
|
242
|
+
mapping_data['md_start'] = int(md_range.get('start', 0))
|
|
243
|
+
mapping_data['md_end'] = int(md_range.get('end', 0))
|
|
244
|
+
|
|
245
|
+
type_elem = mapping.find('type')
|
|
246
|
+
if type_elem is not None:
|
|
247
|
+
mapping_data['type'] = type_elem.text or ''
|
|
248
|
+
|
|
249
|
+
level_elem = mapping.find('level')
|
|
250
|
+
if level_elem is not None:
|
|
251
|
+
mapping_data['level'] = int(level_elem.text or 0)
|
|
252
|
+
|
|
253
|
+
style_elem = mapping.find('style')
|
|
254
|
+
if style_elem is not None:
|
|
255
|
+
mapping_data['style'] = style_elem.text or ''
|
|
256
|
+
|
|
257
|
+
meta_elem = mapping.find('metadata')
|
|
258
|
+
if meta_elem is not None:
|
|
259
|
+
for child in meta_elem:
|
|
260
|
+
key = child.tag.replace('-', '_')
|
|
261
|
+
mapping_data['metadata'][key] = child.text
|
|
262
|
+
|
|
263
|
+
metadata['mappings'].append(mapping_data)
|
|
264
|
+
|
|
265
|
+
# Parse preserved elements
|
|
266
|
+
preserved_elem = root.find('preserved')
|
|
267
|
+
if preserved_elem is not None:
|
|
268
|
+
for element in preserved_elem.findall('element'):
|
|
269
|
+
elem_data = {
|
|
270
|
+
'id': element.get('id', ''),
|
|
271
|
+
'type': element.get('type', ''),
|
|
272
|
+
'ref': element.get('ref', ''),
|
|
273
|
+
'docx_path': '',
|
|
274
|
+
'extracted_path': ''
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
docx_path = element.find('docx-path')
|
|
278
|
+
if docx_path is not None:
|
|
279
|
+
elem_data['docx_path'] = docx_path.text or ''
|
|
280
|
+
|
|
281
|
+
extracted_path = element.find('extracted-path')
|
|
282
|
+
if extracted_path is not None:
|
|
283
|
+
elem_data['extracted_path'] = extracted_path.text or ''
|
|
284
|
+
|
|
285
|
+
metadata['preserved'].append(elem_data)
|
|
286
|
+
|
|
287
|
+
return metadata
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def update_mapping(
|
|
291
|
+
meta_path: Path,
|
|
292
|
+
old_md_content: str,
|
|
293
|
+
new_md_content: str
|
|
294
|
+
) -> Dict[str, Any]:
|
|
295
|
+
"""Update metadata mappings based on Markdown changes.
|
|
296
|
+
|
|
297
|
+
Args:
|
|
298
|
+
meta_path: Path to the metadata XML file.
|
|
299
|
+
old_md_content: Original Markdown content.
|
|
300
|
+
new_md_content: Modified Markdown content.
|
|
301
|
+
|
|
302
|
+
Returns:
|
|
303
|
+
Dictionary with change information.
|
|
304
|
+
"""
|
|
305
|
+
metadata = load_metadata(meta_path)
|
|
306
|
+
|
|
307
|
+
old_lines = old_md_content.split('\n')
|
|
308
|
+
new_lines = new_md_content.split('\n')
|
|
309
|
+
|
|
310
|
+
changes = {
|
|
311
|
+
'modified_mappings': [],
|
|
312
|
+
'line_shifts': {},
|
|
313
|
+
'unchanged_mappings': []
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
# Simple diff: track which line ranges changed
|
|
317
|
+
# This is a basic implementation - a more sophisticated diff
|
|
318
|
+
# would use difflib or similar
|
|
319
|
+
|
|
320
|
+
for mapping in metadata['mappings']:
|
|
321
|
+
start = mapping['md_start'] - 1 # Convert to 0-indexed
|
|
322
|
+
end = mapping['md_end'] - 1
|
|
323
|
+
|
|
324
|
+
if start < 0 or end >= len(old_lines):
|
|
325
|
+
continue
|
|
326
|
+
|
|
327
|
+
old_content = '\n'.join(old_lines[start:end + 1])
|
|
328
|
+
|
|
329
|
+
# Check if this range still exists and matches
|
|
330
|
+
if end < len(new_lines):
|
|
331
|
+
new_content = '\n'.join(new_lines[start:end + 1])
|
|
332
|
+
if old_content == new_content:
|
|
333
|
+
changes['unchanged_mappings'].append(mapping['id'])
|
|
334
|
+
else:
|
|
335
|
+
changes['modified_mappings'].append({
|
|
336
|
+
'id': mapping['id'],
|
|
337
|
+
'old_content': old_content,
|
|
338
|
+
'new_content': new_content
|
|
339
|
+
})
|
|
340
|
+
else:
|
|
341
|
+
changes['modified_mappings'].append({
|
|
342
|
+
'id': mapping['id'],
|
|
343
|
+
'old_content': old_content,
|
|
344
|
+
'new_content': None # Deleted
|
|
345
|
+
})
|
|
346
|
+
|
|
347
|
+
return changes
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def find_metadata_path(md_path: Path) -> Optional[Path]:
|
|
351
|
+
"""Find the metadata file for a given Markdown file.
|
|
352
|
+
|
|
353
|
+
Args:
|
|
354
|
+
md_path: Path to the Markdown file.
|
|
355
|
+
|
|
356
|
+
Returns:
|
|
357
|
+
Path to the metadata file if it exists, None otherwise.
|
|
358
|
+
"""
|
|
359
|
+
meta_path = md_path.parent / f"{md_path.stem}_meta.xml"
|
|
360
|
+
if meta_path.exists():
|
|
361
|
+
return meta_path
|
|
362
|
+
return None
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def get_meta_path(document_path: Path) -> Path:
|
|
366
|
+
"""Get the metadata file path for a document.
|
|
367
|
+
|
|
368
|
+
Args:
|
|
369
|
+
document_path: Path to the Markdown or DOCX file.
|
|
370
|
+
|
|
371
|
+
Returns:
|
|
372
|
+
Path to the corresponding _meta.xml file.
|
|
373
|
+
"""
|
|
374
|
+
return document_path.parent / f"{document_path.stem}_meta.xml"
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def save_metadata_to_both_locations(
|
|
378
|
+
result: 'ExtractionResult',
|
|
379
|
+
source_path: Path,
|
|
380
|
+
output_path: Path
|
|
381
|
+
) -> None:
|
|
382
|
+
"""Save extraction metadata to both source and output locations.
|
|
383
|
+
|
|
384
|
+
Args:
|
|
385
|
+
result: The extraction result containing elements and mappings.
|
|
386
|
+
source_path: Path to the source file (DOCX).
|
|
387
|
+
output_path: Path to the output file (MD).
|
|
388
|
+
"""
|
|
389
|
+
# Get metadata paths for both locations
|
|
390
|
+
source_meta = get_meta_path(source_path)
|
|
391
|
+
output_meta = get_meta_path(output_path)
|
|
392
|
+
|
|
393
|
+
# Save to source location
|
|
394
|
+
save_metadata(result, source_path, output_path, source_meta)
|
|
395
|
+
|
|
396
|
+
# Save to output location if different
|
|
397
|
+
if source_meta != output_meta:
|
|
398
|
+
save_metadata(result, source_path, output_path, output_meta)
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""Add missing Pandoc styles to DOCX documents.
|
|
2
|
+
|
|
3
|
+
Pandoc generates content using styles that may not exist in the template.
|
|
4
|
+
This module ensures those styles are defined to prevent Word from reporting
|
|
5
|
+
unreadable content errors.
|
|
6
|
+
"""
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from docx import Document
|
|
9
|
+
from docx.shared import Pt, Twips
|
|
10
|
+
from docx.enum.style import WD_STYLE_TYPE
|
|
11
|
+
from docx.oxml.ns import qn
|
|
12
|
+
from docx.oxml import OxmlElement
|
|
13
|
+
import logging
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
# Pandoc styles that need to be defined
|
|
18
|
+
PANDOC_STYLES = {
|
|
19
|
+
# Style name: (base style, description)
|
|
20
|
+
'FirstParagraph': ('Normal', 'First paragraph after heading'),
|
|
21
|
+
'BodyText': ('Normal', 'Body text'),
|
|
22
|
+
'Compact': ('Normal', 'Compact paragraph'),
|
|
23
|
+
'ImageCaption': ('Normal', 'Image caption'),
|
|
24
|
+
'CaptionedFigure': ('Normal', 'Figure with caption'),
|
|
25
|
+
'Caption': ('Normal', 'Caption text'),
|
|
26
|
+
'SourceCode': ('Normal', 'Source code block'),
|
|
27
|
+
'Verbatim': ('Normal', 'Verbatim text'),
|
|
28
|
+
'Definition': ('Normal', 'Definition text'),
|
|
29
|
+
'DefinitionTerm': ('Normal', 'Definition term'),
|
|
30
|
+
'BlockQuote': ('Normal', 'Block quote'),
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def ensure_pandoc_styles(docx_path: Path) -> None:
|
|
35
|
+
"""Ensure all Pandoc-generated styles exist in the document.
|
|
36
|
+
|
|
37
|
+
This function adds style definitions for common Pandoc styles
|
|
38
|
+
that may not exist in the template. If a style already exists,
|
|
39
|
+
it is not modified.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
docx_path: Path to the DOCX file to fix.
|
|
43
|
+
"""
|
|
44
|
+
doc = Document(docx_path)
|
|
45
|
+
styles_added = []
|
|
46
|
+
|
|
47
|
+
for style_name, (base_style_name, description) in PANDOC_STYLES.items():
|
|
48
|
+
try:
|
|
49
|
+
# Check if style already exists
|
|
50
|
+
existing = None
|
|
51
|
+
for style in doc.styles:
|
|
52
|
+
if style.name == style_name:
|
|
53
|
+
existing = style
|
|
54
|
+
break
|
|
55
|
+
|
|
56
|
+
if existing is None:
|
|
57
|
+
# Create the style
|
|
58
|
+
try:
|
|
59
|
+
new_style = doc.styles.add_style(style_name, WD_STYLE_TYPE.PARAGRAPH)
|
|
60
|
+
|
|
61
|
+
# Try to base it on the base style
|
|
62
|
+
try:
|
|
63
|
+
base = doc.styles[base_style_name]
|
|
64
|
+
new_style.base_style = base
|
|
65
|
+
except KeyError:
|
|
66
|
+
pass # Use default if base doesn't exist
|
|
67
|
+
|
|
68
|
+
# Set basic formatting based on style type
|
|
69
|
+
if style_name == 'Compact':
|
|
70
|
+
new_style.paragraph_format.space_before = Pt(0)
|
|
71
|
+
new_style.paragraph_format.space_after = Pt(0)
|
|
72
|
+
elif style_name == 'ImageCaption' or style_name == 'Caption':
|
|
73
|
+
new_style.font.italic = True
|
|
74
|
+
new_style.font.size = Pt(10)
|
|
75
|
+
new_style.paragraph_format.space_before = Pt(6)
|
|
76
|
+
elif style_name == 'SourceCode' or style_name == 'Verbatim':
|
|
77
|
+
new_style.font.name = 'Courier New'
|
|
78
|
+
new_style.font.size = Pt(9)
|
|
79
|
+
elif style_name == 'BlockQuote':
|
|
80
|
+
new_style.paragraph_format.left_indent = Twips(720) # 0.5 inch
|
|
81
|
+
new_style.font.italic = True
|
|
82
|
+
|
|
83
|
+
styles_added.append(style_name)
|
|
84
|
+
except ValueError as e:
|
|
85
|
+
# Style might already exist with different ID
|
|
86
|
+
logger.debug(f"Could not add style {style_name}: {e}")
|
|
87
|
+
except Exception as e:
|
|
88
|
+
logger.debug(f"Error processing style {style_name}: {e}")
|
|
89
|
+
|
|
90
|
+
if styles_added:
|
|
91
|
+
logger.info(f"Added missing Pandoc styles: {', '.join(styles_added)}")
|
|
92
|
+
doc.save(docx_path)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def fix_style_references(docx_path: Path) -> None:
|
|
96
|
+
"""Fix any broken style references in the document.
|
|
97
|
+
|
|
98
|
+
This is a more aggressive fix that directly manipulates the XML
|
|
99
|
+
to ensure all referenced styles exist.
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
docx_path: Path to the DOCX file to fix.
|
|
103
|
+
"""
|
|
104
|
+
import zipfile
|
|
105
|
+
import tempfile
|
|
106
|
+
|
|
107
|
+
try:
|
|
108
|
+
from lxml import etree as ET
|
|
109
|
+
USING_LXML = True
|
|
110
|
+
except ImportError:
|
|
111
|
+
from xml.etree import ElementTree as ET
|
|
112
|
+
USING_LXML = False
|
|
113
|
+
|
|
114
|
+
# Namespaces - register all Word namespaces
|
|
115
|
+
namespaces = {
|
|
116
|
+
'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main',
|
|
117
|
+
'r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
|
|
118
|
+
'wp': 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing',
|
|
119
|
+
'a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
|
|
120
|
+
'pic': 'http://schemas.openxmlformats.org/drawingml/2006/picture',
|
|
121
|
+
'v': 'urn:schemas-microsoft-com:vml',
|
|
122
|
+
'o': 'urn:schemas-microsoft-com:office:office',
|
|
123
|
+
'm': 'http://schemas.openxmlformats.org/officeDocument/2006/math',
|
|
124
|
+
'w10': 'urn:schemas-microsoft-com:office:word',
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if not USING_LXML:
|
|
128
|
+
for prefix, uri in namespaces.items():
|
|
129
|
+
ET.register_namespace(prefix, uri)
|
|
130
|
+
|
|
131
|
+
w_ns = namespaces['w']
|
|
132
|
+
|
|
133
|
+
# Extract and analyze
|
|
134
|
+
with tempfile.TemporaryDirectory() as temp_dir:
|
|
135
|
+
temp_path = Path(temp_dir)
|
|
136
|
+
|
|
137
|
+
# Extract docx
|
|
138
|
+
with zipfile.ZipFile(docx_path, 'r') as zf:
|
|
139
|
+
zf.extractall(temp_path)
|
|
140
|
+
|
|
141
|
+
# Read document.xml to find all referenced styles
|
|
142
|
+
doc_xml_path = temp_path / 'word' / 'document.xml'
|
|
143
|
+
styles_xml_path = temp_path / 'word' / 'styles.xml'
|
|
144
|
+
|
|
145
|
+
if not doc_xml_path.exists() or not styles_xml_path.exists():
|
|
146
|
+
return
|
|
147
|
+
|
|
148
|
+
# Parse document to find referenced styles
|
|
149
|
+
if USING_LXML:
|
|
150
|
+
parser = ET.XMLParser(remove_blank_text=False)
|
|
151
|
+
doc_tree = ET.parse(str(doc_xml_path), parser)
|
|
152
|
+
else:
|
|
153
|
+
doc_tree = ET.parse(doc_xml_path)
|
|
154
|
+
doc_root = doc_tree.getroot()
|
|
155
|
+
|
|
156
|
+
# Find all style references
|
|
157
|
+
referenced_styles = set()
|
|
158
|
+
if USING_LXML:
|
|
159
|
+
for pStyle in doc_root.iter(f'{{{w_ns}}}pStyle'):
|
|
160
|
+
style_val = pStyle.get(f'{{{w_ns}}}val')
|
|
161
|
+
if style_val:
|
|
162
|
+
referenced_styles.add(style_val)
|
|
163
|
+
else:
|
|
164
|
+
for pStyle in doc_root.iter(f'{{{w_ns}}}pStyle'):
|
|
165
|
+
style_val = pStyle.get(f'{{{w_ns}}}val')
|
|
166
|
+
if style_val:
|
|
167
|
+
referenced_styles.add(style_val)
|
|
168
|
+
|
|
169
|
+
# Parse styles.xml
|
|
170
|
+
if USING_LXML:
|
|
171
|
+
styles_tree = ET.parse(str(styles_xml_path), parser)
|
|
172
|
+
else:
|
|
173
|
+
styles_tree = ET.parse(styles_xml_path)
|
|
174
|
+
styles_root = styles_tree.getroot()
|
|
175
|
+
|
|
176
|
+
# Find defined styles
|
|
177
|
+
defined_styles = set()
|
|
178
|
+
for style in styles_root.iter(f'{{{w_ns}}}style'):
|
|
179
|
+
style_id = style.get(f'{{{w_ns}}}styleId')
|
|
180
|
+
if style_id:
|
|
181
|
+
defined_styles.add(style_id)
|
|
182
|
+
|
|
183
|
+
# Find missing styles
|
|
184
|
+
missing_styles = referenced_styles - defined_styles
|
|
185
|
+
|
|
186
|
+
if missing_styles:
|
|
187
|
+
logger.info(f"Found missing style definitions: {missing_styles}")
|
|
188
|
+
|
|
189
|
+
# Add missing styles
|
|
190
|
+
for style_name in missing_styles:
|
|
191
|
+
style_elem = ET.SubElement(styles_root, f'{{{w_ns}}}style')
|
|
192
|
+
style_elem.set(f'{{{w_ns}}}type', 'paragraph')
|
|
193
|
+
style_elem.set(f'{{{w_ns}}}styleId', style_name)
|
|
194
|
+
style_elem.set(f'{{{w_ns}}}customStyle', '1')
|
|
195
|
+
|
|
196
|
+
name_elem = ET.SubElement(style_elem, f'{{{w_ns}}}name')
|
|
197
|
+
name_elem.set(f'{{{w_ns}}}val', style_name)
|
|
198
|
+
|
|
199
|
+
# Base on Normal
|
|
200
|
+
basedOn = ET.SubElement(style_elem, f'{{{w_ns}}}basedOn')
|
|
201
|
+
basedOn.set(f'{{{w_ns}}}val', 'Normal')
|
|
202
|
+
|
|
203
|
+
# Save modified styles.xml
|
|
204
|
+
if USING_LXML:
|
|
205
|
+
styles_tree.write(str(styles_xml_path), encoding='UTF-8', xml_declaration=True)
|
|
206
|
+
else:
|
|
207
|
+
styles_tree.write(styles_xml_path, encoding='UTF-8', xml_declaration=True)
|
|
208
|
+
|
|
209
|
+
# Repackage docx - ensure [Content_Types].xml is first
|
|
210
|
+
with zipfile.ZipFile(docx_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
|
211
|
+
# Write [Content_Types].xml first (required by OOXML spec)
|
|
212
|
+
content_types = temp_path / '[Content_Types].xml'
|
|
213
|
+
if content_types.exists():
|
|
214
|
+
zf.write(content_types, '[Content_Types].xml')
|
|
215
|
+
|
|
216
|
+
# Write remaining files
|
|
217
|
+
for file_path in sorted(temp_path.rglob('*')):
|
|
218
|
+
if file_path.is_file() and file_path.name != '[Content_Types].xml':
|
|
219
|
+
arcname = file_path.relative_to(temp_path)
|
|
220
|
+
zf.write(file_path, arcname)
|
|
221
|
+
|
|
222
|
+
logger.info(f"Added {len(missing_styles)} missing style definitions")
|