@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,534 @@
|
|
|
1
|
+
"""AsciiDoc document conversion logic.
|
|
2
|
+
|
|
3
|
+
Provides bidirectional conversion between AsciiDoc and DOCX formats,
|
|
4
|
+
including support for Mermaid and PlantUML diagrams.
|
|
5
|
+
"""
|
|
6
|
+
import logging
|
|
7
|
+
import re
|
|
8
|
+
import shutil
|
|
9
|
+
import subprocess
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
12
|
+
|
|
13
|
+
import pypandoc
|
|
14
|
+
|
|
15
|
+
from .mermaid_renderer import render_all_diagrams, DiagramFormat, resolve_diagram_format
|
|
16
|
+
from .svg_embedder import is_svg_embedding_available
|
|
17
|
+
from .plantuml_renderer import (
|
|
18
|
+
has_plantuml_blocks,
|
|
19
|
+
render_all_plantuml_diagrams,
|
|
20
|
+
PlantUMLRenderError
|
|
21
|
+
)
|
|
22
|
+
from .utils import create_temp_dir, cleanup_temp_files
|
|
23
|
+
from .frontmatter_parser import (
|
|
24
|
+
parse_frontmatter,
|
|
25
|
+
extract_template_config,
|
|
26
|
+
extract_variables,
|
|
27
|
+
extract_conversion_options,
|
|
28
|
+
extract_table_style,
|
|
29
|
+
warn_unknown_keys,
|
|
30
|
+
)
|
|
31
|
+
from .system_variables import (
|
|
32
|
+
resolve_system_variables,
|
|
33
|
+
detect_toc_placeholder,
|
|
34
|
+
SystemContext,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
logger = logging.getLogger(__name__)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
# Regex patterns for Mermaid blocks in AsciiDoc
|
|
41
|
+
MERMAID_ASCIIDOC_PATTERN = re.compile(
|
|
42
|
+
r'\[(source,)?mermaid\]\s*\n----\s*\n(.*?)----',
|
|
43
|
+
re.DOTALL
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def check_pandoc_available() -> bool:
|
|
48
|
+
"""Check if pandoc is available.
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
True if pandoc is installed and accessible.
|
|
52
|
+
"""
|
|
53
|
+
try:
|
|
54
|
+
result = subprocess.run(
|
|
55
|
+
['pandoc', '--version'],
|
|
56
|
+
capture_output=True,
|
|
57
|
+
timeout=10
|
|
58
|
+
)
|
|
59
|
+
return result.returncode == 0
|
|
60
|
+
except (FileNotFoundError, subprocess.TimeoutExpired):
|
|
61
|
+
return False
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def detect_input_format(file_path: Path) -> Optional[str]:
|
|
65
|
+
"""Detect input format based on file extension.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
file_path: Path to the input file.
|
|
69
|
+
|
|
70
|
+
Returns:
|
|
71
|
+
Format string ('asciidoc', 'markdown') or None if unknown.
|
|
72
|
+
"""
|
|
73
|
+
ext = file_path.suffix.lower()
|
|
74
|
+
|
|
75
|
+
if ext in ('.adoc', '.asciidoc', '.asc'):
|
|
76
|
+
return 'asciidoc'
|
|
77
|
+
elif ext in ('.md', '.markdown'):
|
|
78
|
+
return 'markdown'
|
|
79
|
+
else:
|
|
80
|
+
return None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def extract_mermaid_blocks_adoc(content: str) -> List[str]:
|
|
84
|
+
"""Extract Mermaid diagram blocks from AsciiDoc content.
|
|
85
|
+
|
|
86
|
+
Supports both [source,mermaid] and [mermaid] block syntaxes.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
content: AsciiDoc content.
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
List of Mermaid diagram code strings.
|
|
93
|
+
"""
|
|
94
|
+
matches = MERMAID_ASCIIDOC_PATTERN.findall(content)
|
|
95
|
+
# Each match is a tuple (source_prefix, diagram_code)
|
|
96
|
+
return [match[1].strip() for match in matches]
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def has_mermaid_blocks_adoc(content: str) -> bool:
|
|
100
|
+
"""Check if AsciiDoc content contains Mermaid blocks.
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
content: AsciiDoc content.
|
|
104
|
+
|
|
105
|
+
Returns:
|
|
106
|
+
True if Mermaid blocks are found.
|
|
107
|
+
"""
|
|
108
|
+
return bool(MERMAID_ASCIIDOC_PATTERN.search(content))
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def replace_mermaid_with_images_adoc(
|
|
112
|
+
content: str,
|
|
113
|
+
diagram_map: Dict[str, Path],
|
|
114
|
+
relative_to: Optional[Path] = None
|
|
115
|
+
) -> str:
|
|
116
|
+
"""Replace Mermaid blocks in AsciiDoc with image references.
|
|
117
|
+
|
|
118
|
+
Args:
|
|
119
|
+
content: AsciiDoc content with Mermaid blocks.
|
|
120
|
+
diagram_map: Mapping of Mermaid code to image paths.
|
|
121
|
+
relative_to: Optional path to make image references relative to.
|
|
122
|
+
|
|
123
|
+
Returns:
|
|
124
|
+
Modified AsciiDoc with image macros instead of Mermaid blocks.
|
|
125
|
+
"""
|
|
126
|
+
# Build list of image references in order
|
|
127
|
+
image_refs = []
|
|
128
|
+
for mermaid_code, image_path in diagram_map.items():
|
|
129
|
+
if relative_to:
|
|
130
|
+
try:
|
|
131
|
+
rel_path = image_path.relative_to(relative_to)
|
|
132
|
+
image_ref = f"image::{rel_path}[Diagram]"
|
|
133
|
+
except ValueError:
|
|
134
|
+
image_ref = f"image::{image_path.name}[Diagram]"
|
|
135
|
+
else:
|
|
136
|
+
image_ref = f"image::{image_path.name}[Diagram]"
|
|
137
|
+
image_refs.append(image_ref)
|
|
138
|
+
|
|
139
|
+
# Replace all mermaid blocks in order
|
|
140
|
+
idx = 0
|
|
141
|
+
|
|
142
|
+
def replacer(match):
|
|
143
|
+
nonlocal idx
|
|
144
|
+
if idx < len(image_refs):
|
|
145
|
+
result = image_refs[idx]
|
|
146
|
+
idx += 1
|
|
147
|
+
return result
|
|
148
|
+
return match.group(0)
|
|
149
|
+
|
|
150
|
+
modified = MERMAID_ASCIIDOC_PATTERN.sub(replacer, content)
|
|
151
|
+
return modified
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def render_mermaid_diagrams_adoc(
|
|
155
|
+
content: str,
|
|
156
|
+
temp_dir: Path,
|
|
157
|
+
width: int = 1200,
|
|
158
|
+
scale: int = 2,
|
|
159
|
+
format: str = "png"
|
|
160
|
+
) -> Tuple[str, Dict[str, Path]]:
|
|
161
|
+
"""Render Mermaid diagrams in AsciiDoc content.
|
|
162
|
+
|
|
163
|
+
Args:
|
|
164
|
+
content: AsciiDoc content with Mermaid blocks.
|
|
165
|
+
temp_dir: Temporary directory for output images.
|
|
166
|
+
width: Maximum width for diagrams in pixels.
|
|
167
|
+
scale: Scale factor for diagram resolution.
|
|
168
|
+
format: Output format - 'png' or 'svg' (default: 'png').
|
|
169
|
+
|
|
170
|
+
Returns:
|
|
171
|
+
Tuple of (modified content, diagram map).
|
|
172
|
+
"""
|
|
173
|
+
if not has_mermaid_blocks_adoc(content):
|
|
174
|
+
return content, {}
|
|
175
|
+
|
|
176
|
+
# Extract blocks and render
|
|
177
|
+
blocks = extract_mermaid_blocks_adoc(content)
|
|
178
|
+
diagram_map = render_all_diagrams(content, temp_dir, width=width, scale=scale, format=format)
|
|
179
|
+
|
|
180
|
+
# Replace blocks with images
|
|
181
|
+
modified = replace_mermaid_with_images_adoc(content, diagram_map, relative_to=temp_dir)
|
|
182
|
+
return modified, diagram_map
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def convert_adoc_to_docx(
|
|
186
|
+
input_path: str | Path,
|
|
187
|
+
output_path: str | Path,
|
|
188
|
+
template_path: Optional[str | Path] = None,
|
|
189
|
+
template_name: Optional[str] = None,
|
|
190
|
+
templates_dir: Optional[str | Path] = None,
|
|
191
|
+
enable_toc: bool = True,
|
|
192
|
+
toc_heading: str = "Table of Contents",
|
|
193
|
+
diagram_width: int = 1200,
|
|
194
|
+
diagram_scale: int = 2,
|
|
195
|
+
diagram_format: str | DiagramFormat = "png",
|
|
196
|
+
embed_svg_in_word: bool = False,
|
|
197
|
+
debug: bool = False,
|
|
198
|
+
variables: Optional[Dict[str, str]] = None
|
|
199
|
+
) -> None:
|
|
200
|
+
"""Convert AsciiDoc file to DOCX.
|
|
201
|
+
|
|
202
|
+
Args:
|
|
203
|
+
input_path: Path to input AsciiDoc file.
|
|
204
|
+
output_path: Path to output DOCX file.
|
|
205
|
+
template_path: Optional path to DOCX template for styling.
|
|
206
|
+
template_name: Name of a template to use from templates directory.
|
|
207
|
+
templates_dir: Directory containing templates.
|
|
208
|
+
enable_toc: Whether to include a Table of Contents.
|
|
209
|
+
toc_heading: Heading text for the TOC.
|
|
210
|
+
diagram_width: Maximum width for diagrams in pixels.
|
|
211
|
+
diagram_scale: Scale factor for diagram resolution.
|
|
212
|
+
diagram_format: Output format for diagrams - 'png', 'svg', or 'auto' (default: 'png').
|
|
213
|
+
embed_svg_in_word: Whether to embed SVG directly in Word (experimental, default: False).
|
|
214
|
+
debug: Whether to save intermediate files for debugging.
|
|
215
|
+
variables: Dictionary of variable names to values for template substitution.
|
|
216
|
+
|
|
217
|
+
Raises:
|
|
218
|
+
FileNotFoundError: If input file does not exist.
|
|
219
|
+
RuntimeError: If pandoc is not available or conversion fails.
|
|
220
|
+
"""
|
|
221
|
+
input_path = Path(input_path)
|
|
222
|
+
output_path = Path(output_path)
|
|
223
|
+
|
|
224
|
+
# Validate input file
|
|
225
|
+
if not input_path.exists():
|
|
226
|
+
raise FileNotFoundError(f"Input file does not exist: {input_path}")
|
|
227
|
+
|
|
228
|
+
# Check pandoc availability
|
|
229
|
+
if not check_pandoc_available():
|
|
230
|
+
raise RuntimeError(
|
|
231
|
+
"Pandoc is not installed. "
|
|
232
|
+
"Please install it: brew install pandoc (macOS) or apt install pandoc (Linux)"
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
# Read AsciiDoc content
|
|
236
|
+
adoc_content = input_path.read_text(encoding='utf-8')
|
|
237
|
+
|
|
238
|
+
# Parse frontmatter (supports both YAML frontmatter and AsciiDoc native attributes)
|
|
239
|
+
frontmatter, content_without_frontmatter = parse_frontmatter(adoc_content, format='asciidoc')
|
|
240
|
+
|
|
241
|
+
# Check for deprecated properties file
|
|
242
|
+
properties_file = input_path.with_suffix('.properties')
|
|
243
|
+
if properties_file.exists():
|
|
244
|
+
logger.warning(
|
|
245
|
+
f"Deprecated: Properties file '{properties_file.name}' found. "
|
|
246
|
+
"Please migrate to YAML frontmatter. Properties files will be removed in a future version."
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
# Extract configuration from frontmatter
|
|
250
|
+
fm_template_config = extract_template_config(frontmatter)
|
|
251
|
+
fm_conversion_options = extract_conversion_options(frontmatter)
|
|
252
|
+
|
|
253
|
+
# Merge frontmatter settings with function parameters (CLI takes priority)
|
|
254
|
+
# Template settings: CLI > frontmatter
|
|
255
|
+
if template_name is None and fm_template_config.get('template'):
|
|
256
|
+
template_name = fm_template_config['template']
|
|
257
|
+
if templates_dir is None and fm_template_config.get('templates_dir'):
|
|
258
|
+
templates_dir = fm_template_config['templates_dir']
|
|
259
|
+
|
|
260
|
+
# Conversion options: CLI > frontmatter > defaults
|
|
261
|
+
language = frontmatter.get('language', 'en')
|
|
262
|
+
if enable_toc and 'enable_toc' in fm_conversion_options:
|
|
263
|
+
enable_toc = fm_conversion_options['enable_toc']
|
|
264
|
+
if toc_heading == "Table of Contents" and 'toc_heading' in fm_conversion_options:
|
|
265
|
+
toc_heading = fm_conversion_options['toc_heading']
|
|
266
|
+
if diagram_format == "png" and 'diagram_format' in fm_conversion_options:
|
|
267
|
+
diagram_format = fm_conversion_options['diagram_format']
|
|
268
|
+
if diagram_width == 1200 and 'diagram_width' in fm_conversion_options:
|
|
269
|
+
diagram_width = fm_conversion_options['diagram_width']
|
|
270
|
+
if diagram_scale == 2 and 'diagram_scale' in fm_conversion_options:
|
|
271
|
+
diagram_scale = fm_conversion_options['diagram_scale']
|
|
272
|
+
if not embed_svg_in_word and 'embed_svg_in_word' in fm_conversion_options:
|
|
273
|
+
embed_svg_in_word = fm_conversion_options['embed_svg_in_word']
|
|
274
|
+
if not debug and 'debug' in fm_conversion_options:
|
|
275
|
+
debug = fm_conversion_options['debug']
|
|
276
|
+
|
|
277
|
+
# Build system context for variable resolution
|
|
278
|
+
# Use output filename (.docx) instead of input filename (.adoc/.md) for $fileName variable
|
|
279
|
+
system_context = SystemContext(
|
|
280
|
+
file_name=output_path.name,
|
|
281
|
+
language=language,
|
|
282
|
+
has_toc_placeholder=detect_toc_placeholder(content_without_frontmatter) is not None
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
# Extract template variables from frontmatter
|
|
286
|
+
known_vars = list(frontmatter.keys())
|
|
287
|
+
fm_variables = extract_variables(frontmatter, known_vars)
|
|
288
|
+
|
|
289
|
+
# Warn about unknown keys
|
|
290
|
+
warn_unknown_keys(frontmatter, known_vars)
|
|
291
|
+
|
|
292
|
+
# Merge variables: CLI > frontmatter
|
|
293
|
+
if variables is None:
|
|
294
|
+
variables = {}
|
|
295
|
+
merged_variables = {**fm_variables, **variables}
|
|
296
|
+
|
|
297
|
+
# Resolve system variables in variable values
|
|
298
|
+
for key, value in merged_variables.items():
|
|
299
|
+
if isinstance(value, str):
|
|
300
|
+
merged_variables[key] = resolve_system_variables(value, system_context)
|
|
301
|
+
|
|
302
|
+
# Resolve system variables in content
|
|
303
|
+
adoc_content = resolve_system_variables(content_without_frontmatter, system_context)
|
|
304
|
+
|
|
305
|
+
# Create temporary directory for diagrams
|
|
306
|
+
temp_dir = create_temp_dir()
|
|
307
|
+
|
|
308
|
+
try:
|
|
309
|
+
# Resolve diagram format
|
|
310
|
+
if isinstance(diagram_format, str):
|
|
311
|
+
diagram_format_enum = DiagramFormat(diagram_format)
|
|
312
|
+
else:
|
|
313
|
+
diagram_format_enum = diagram_format
|
|
314
|
+
|
|
315
|
+
# Determine actual format based on output type
|
|
316
|
+
output_suffix = output_path.suffix
|
|
317
|
+
actual_format = resolve_diagram_format(output_suffix, diagram_format_enum)
|
|
318
|
+
|
|
319
|
+
# For DOCX output with SVG, check if we need to fall back to PNG
|
|
320
|
+
if output_suffix.lower() == '.docx' and actual_format == 'svg':
|
|
321
|
+
if not embed_svg_in_word:
|
|
322
|
+
# User wants SVG but not embedding in Word - fall back to PNG for compatibility
|
|
323
|
+
actual_format = 'png'
|
|
324
|
+
elif not is_svg_embedding_available():
|
|
325
|
+
# User requested SVG embedding but python-docx-ng is not installed
|
|
326
|
+
print("Warning: SVG embedding in Word requires python-docx-ng. "
|
|
327
|
+
"Install with: pip install python-docx-ng")
|
|
328
|
+
print("Falling back to PNG format for diagrams.")
|
|
329
|
+
actual_format = 'png'
|
|
330
|
+
|
|
331
|
+
# Render Mermaid diagrams
|
|
332
|
+
modified_content, diagram_map = render_mermaid_diagrams_adoc(
|
|
333
|
+
adoc_content,
|
|
334
|
+
temp_dir,
|
|
335
|
+
width=diagram_width,
|
|
336
|
+
scale=diagram_scale,
|
|
337
|
+
format=actual_format
|
|
338
|
+
)
|
|
339
|
+
|
|
340
|
+
# Render PlantUML diagrams if present
|
|
341
|
+
if has_plantuml_blocks(modified_content, format='asciidoc'):
|
|
342
|
+
try:
|
|
343
|
+
plantuml_result = render_all_plantuml_diagrams(
|
|
344
|
+
modified_content,
|
|
345
|
+
output_dir=temp_dir,
|
|
346
|
+
format='asciidoc',
|
|
347
|
+
image_format=actual_format,
|
|
348
|
+
fail_on_error=False
|
|
349
|
+
)
|
|
350
|
+
modified_content = plantuml_result['content']
|
|
351
|
+
if plantuml_result.get('warnings'):
|
|
352
|
+
for warning in plantuml_result['warnings']:
|
|
353
|
+
print(f"PlantUML warning: {warning}")
|
|
354
|
+
except PlantUMLRenderError as e:
|
|
355
|
+
print(f"PlantUML rendering skipped: {e}")
|
|
356
|
+
|
|
357
|
+
# Save modified content to temp file
|
|
358
|
+
temp_adoc = temp_dir / "modified.adoc"
|
|
359
|
+
temp_adoc.write_text(modified_content, encoding='utf-8')
|
|
360
|
+
|
|
361
|
+
if debug:
|
|
362
|
+
debug_path = output_path.parent / f"{output_path.stem}_debug.adoc"
|
|
363
|
+
shutil.copy2(temp_adoc, debug_path)
|
|
364
|
+
|
|
365
|
+
# Build pandoc arguments
|
|
366
|
+
pandoc_args = ['--standalone']
|
|
367
|
+
|
|
368
|
+
# Add resource path for images
|
|
369
|
+
pandoc_args.append(f'--resource-path={temp_dir}:{input_path.parent}')
|
|
370
|
+
|
|
371
|
+
# Add TOC if enabled
|
|
372
|
+
if enable_toc:
|
|
373
|
+
pandoc_args.append('--toc')
|
|
374
|
+
pandoc_args.append(f'--toc-depth=3')
|
|
375
|
+
|
|
376
|
+
# Use template as reference document if available
|
|
377
|
+
if template_path:
|
|
378
|
+
template_path = Path(template_path)
|
|
379
|
+
if template_path.exists():
|
|
380
|
+
pandoc_args.append(f'--reference-doc={template_path}')
|
|
381
|
+
|
|
382
|
+
# Convert using pypandoc
|
|
383
|
+
pypandoc.convert_file(
|
|
384
|
+
str(temp_adoc),
|
|
385
|
+
'docx',
|
|
386
|
+
format='asciidoc',
|
|
387
|
+
outputfile=str(output_path),
|
|
388
|
+
extra_args=pandoc_args
|
|
389
|
+
)
|
|
390
|
+
|
|
391
|
+
# Validate output was created
|
|
392
|
+
if not output_path.exists():
|
|
393
|
+
raise RuntimeError(f"Failed to create output file: {output_path}")
|
|
394
|
+
|
|
395
|
+
finally:
|
|
396
|
+
cleanup_temp_files(temp_dir)
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def extract_docx_to_adoc(
|
|
400
|
+
input_path: str | Path,
|
|
401
|
+
output_path: str | Path,
|
|
402
|
+
extract_images: bool = True,
|
|
403
|
+
images_dir: Optional[str | Path] = None
|
|
404
|
+
) -> None:
|
|
405
|
+
"""Extract content from DOCX to AsciiDoc format.
|
|
406
|
+
|
|
407
|
+
Args:
|
|
408
|
+
input_path: Path to input DOCX file.
|
|
409
|
+
output_path: Path to output AsciiDoc file.
|
|
410
|
+
extract_images: Whether to extract embedded images.
|
|
411
|
+
images_dir: Directory for extracted images (default: same as output).
|
|
412
|
+
|
|
413
|
+
Raises:
|
|
414
|
+
FileNotFoundError: If input file does not exist.
|
|
415
|
+
RuntimeError: If pandoc is not available or extraction fails.
|
|
416
|
+
"""
|
|
417
|
+
input_path = Path(input_path)
|
|
418
|
+
output_path = Path(output_path)
|
|
419
|
+
|
|
420
|
+
# Validate input file
|
|
421
|
+
if not input_path.exists():
|
|
422
|
+
raise FileNotFoundError(f"Input file does not exist: {input_path}")
|
|
423
|
+
|
|
424
|
+
# Check pandoc availability
|
|
425
|
+
if not check_pandoc_available():
|
|
426
|
+
raise RuntimeError(
|
|
427
|
+
"Pandoc is not installed. "
|
|
428
|
+
"Please install it: brew install pandoc (macOS) or apt install pandoc (Linux)"
|
|
429
|
+
)
|
|
430
|
+
|
|
431
|
+
# Determine images directory
|
|
432
|
+
if images_dir is None:
|
|
433
|
+
images_dir = output_path.parent / "images"
|
|
434
|
+
else:
|
|
435
|
+
images_dir = Path(images_dir)
|
|
436
|
+
|
|
437
|
+
# Build pandoc arguments
|
|
438
|
+
pandoc_args = ['--standalone']
|
|
439
|
+
|
|
440
|
+
if extract_images:
|
|
441
|
+
images_dir.mkdir(parents=True, exist_ok=True)
|
|
442
|
+
pandoc_args.append(f'--extract-media={images_dir}')
|
|
443
|
+
|
|
444
|
+
# Convert using pypandoc
|
|
445
|
+
adoc_content = pypandoc.convert_file(
|
|
446
|
+
str(input_path),
|
|
447
|
+
'asciidoc',
|
|
448
|
+
to='asciidoc',
|
|
449
|
+
extra_args=pandoc_args
|
|
450
|
+
)
|
|
451
|
+
|
|
452
|
+
# Write output file
|
|
453
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
454
|
+
output_path.write_text(adoc_content, encoding='utf-8')
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def convert_to_docx(
|
|
458
|
+
input_path: str | Path,
|
|
459
|
+
output_path: str | Path,
|
|
460
|
+
template_path: Optional[str | Path] = None,
|
|
461
|
+
**kwargs
|
|
462
|
+
) -> None:
|
|
463
|
+
"""Convert document to DOCX with automatic format detection.
|
|
464
|
+
|
|
465
|
+
Detects input format based on file extension and uses the appropriate
|
|
466
|
+
converter (Markdown or AsciiDoc).
|
|
467
|
+
|
|
468
|
+
Args:
|
|
469
|
+
input_path: Path to input file (.md, .markdown, .adoc, .asciidoc, .asc).
|
|
470
|
+
output_path: Path to output DOCX file.
|
|
471
|
+
template_path: Optional path to DOCX template for styling.
|
|
472
|
+
**kwargs: Additional arguments passed to the specific converter.
|
|
473
|
+
|
|
474
|
+
Raises:
|
|
475
|
+
FileNotFoundError: If input file does not exist.
|
|
476
|
+
ValueError: If input format cannot be detected.
|
|
477
|
+
RuntimeError: If conversion fails.
|
|
478
|
+
"""
|
|
479
|
+
input_path = Path(input_path)
|
|
480
|
+
|
|
481
|
+
# Detect format
|
|
482
|
+
format_type = detect_input_format(input_path)
|
|
483
|
+
|
|
484
|
+
if format_type is None:
|
|
485
|
+
raise ValueError(
|
|
486
|
+
f"Cannot detect format for file: {input_path}. "
|
|
487
|
+
"Supported extensions: .md, .markdown, .adoc, .asciidoc, .asc"
|
|
488
|
+
)
|
|
489
|
+
|
|
490
|
+
if format_type == 'asciidoc':
|
|
491
|
+
convert_adoc_to_docx(input_path, output_path, template_path=template_path, **kwargs)
|
|
492
|
+
else:
|
|
493
|
+
# Use the existing Markdown converter
|
|
494
|
+
from .converter import convert_md_to_docx
|
|
495
|
+
convert_md_to_docx(input_path, output_path, template_path=template_path, **kwargs)
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def extract_from_docx(
|
|
499
|
+
input_path: str | Path,
|
|
500
|
+
output_path: str | Path,
|
|
501
|
+
**kwargs
|
|
502
|
+
) -> None:
|
|
503
|
+
"""Extract content from DOCX with automatic format detection.
|
|
504
|
+
|
|
505
|
+
Detects output format based on file extension and uses the appropriate
|
|
506
|
+
extractor (Markdown or AsciiDoc).
|
|
507
|
+
|
|
508
|
+
Args:
|
|
509
|
+
input_path: Path to input DOCX file.
|
|
510
|
+
output_path: Path to output file (.md, .markdown, .adoc, .asciidoc, .asc).
|
|
511
|
+
**kwargs: Additional arguments passed to the specific extractor.
|
|
512
|
+
|
|
513
|
+
Raises:
|
|
514
|
+
FileNotFoundError: If input file does not exist.
|
|
515
|
+
ValueError: If output format cannot be detected.
|
|
516
|
+
RuntimeError: If extraction fails.
|
|
517
|
+
"""
|
|
518
|
+
output_path = Path(output_path)
|
|
519
|
+
|
|
520
|
+
# Detect format from output path
|
|
521
|
+
format_type = detect_input_format(output_path)
|
|
522
|
+
|
|
523
|
+
if format_type is None:
|
|
524
|
+
raise ValueError(
|
|
525
|
+
f"Cannot detect format for output file: {output_path}. "
|
|
526
|
+
"Supported extensions: .md, .markdown, .adoc, .asciidoc, .asc"
|
|
527
|
+
)
|
|
528
|
+
|
|
529
|
+
if format_type == 'asciidoc':
|
|
530
|
+
extract_docx_to_adoc(input_path, output_path, **kwargs)
|
|
531
|
+
else:
|
|
532
|
+
# Use the existing Markdown extractor
|
|
533
|
+
from .docx_reader import extract_docx_to_markdown
|
|
534
|
+
extract_docx_to_markdown(input_path, output_path, **kwargs)
|