@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,751 @@
1
+ """Command-line interface for document converter."""
2
+ import argparse
3
+ import glob
4
+ import logging
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from .converter import convert_md_to_docx
9
+ from .manifest_manager import (
10
+ save_manifest_to_both_locations,
11
+ resolve_template_name
12
+ )
13
+ from .variable_manager import (
14
+ get_properties_path,
15
+ load_properties_file,
16
+ save_properties_file,
17
+ resolve_variables
18
+ )
19
+ from .frontmatter_parser import parse_frontmatter, extract_template_config, extract_variables
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ def add_common_args(parser: argparse.ArgumentParser) -> None:
25
+ """Add common arguments to a parser."""
26
+ parser.add_argument(
27
+ '--templates-dir',
28
+ type=str,
29
+ default=None,
30
+ help='Path to templates directory (default: ./templates)'
31
+ )
32
+
33
+
34
+ def cmd_convert(args: argparse.Namespace) -> int:
35
+ """Handle the convert command (MD to DOCX)."""
36
+ from .template_manager import resolve_templates_dir
37
+
38
+ input_path = Path(args.input)
39
+ output_path = Path(args.output)
40
+
41
+ if not input_path.exists():
42
+ print(f"Error: Input file not found: {args.input}", file=sys.stderr)
43
+ return 1
44
+
45
+ # Parse frontmatter if not ignored
46
+ frontmatter = {}
47
+ fm_template_config = {}
48
+ if not getattr(args, 'ignore_frontmatter', False):
49
+ content = input_path.read_text(encoding='utf-8')
50
+ frontmatter, _ = parse_frontmatter(content, format='markdown')
51
+ fm_template_config = extract_template_config(frontmatter)
52
+
53
+ if frontmatter:
54
+ logger.info(f"Frontmatter parsed: {len(frontmatter)} keys")
55
+
56
+ # Resolve template name using fallback chain:
57
+ # 1. CLI argument (--template-name)
58
+ # 2. Frontmatter template
59
+ # 3. Markdown manifest (if exists)
60
+ # 4. Associated DOCX manifest (if exists)
61
+ template_name = args.template_name
62
+ if template_name is None and fm_template_config.get('template'):
63
+ template_name = fm_template_config['template']
64
+ print(f"Using template from frontmatter: {template_name}")
65
+
66
+ if template_name is None:
67
+ template_name = resolve_template_name(
68
+ md_path=input_path,
69
+ docx_path=output_path if output_path.suffix == '.docx' else None,
70
+ cli_template=None
71
+ )
72
+
73
+ print(f"Converting: {args.input}")
74
+ print(f"Output: {args.output}")
75
+ if args.document_name:
76
+ print(f"Document Name: {args.document_name}")
77
+ if args.document_title:
78
+ print(f"Document Title: {args.document_title}")
79
+ if template_name:
80
+ source = "(CLI)" if args.template_name else "(from frontmatter/manifest)"
81
+ print(f"Template: {template_name} {source}")
82
+ if args.template_path:
83
+ print(f"Template Path: {args.template_path}")
84
+ if getattr(args, 'language', None):
85
+ print(f"Language: {args.language}")
86
+
87
+ # Handle variable resolution if using a template
88
+ variables = {}
89
+
90
+ # First, extract variables from frontmatter (if not ignoring frontmatter)
91
+ frontmatter_vars = {}
92
+ if not getattr(args, 'ignore_frontmatter', False):
93
+ try:
94
+ content = input_path.read_text(encoding='utf-8')
95
+ frontmatter, _ = parse_frontmatter(content)
96
+ frontmatter_vars = extract_variables(frontmatter)
97
+ if frontmatter_vars:
98
+ print(f"Frontmatter variables: {len(frontmatter_vars)}")
99
+ except Exception as e:
100
+ print(f"Warning: Could not parse frontmatter: {e}")
101
+
102
+ if template_name and not args.template_path:
103
+ templates_dir = resolve_templates_dir(args.templates_dir)
104
+ template_dir = templates_dir / template_name
105
+
106
+ if template_dir.exists():
107
+ # Load properties file if it exists
108
+ properties_path = get_properties_path(input_path)
109
+ interactive = not getattr(args, 'non_interactive', False)
110
+
111
+ try:
112
+ # Get template defaults, but frontmatter vars take priority
113
+ template_vars = resolve_variables(
114
+ template_dir=template_dir,
115
+ properties_path=properties_path,
116
+ interactive=interactive,
117
+ provided=frontmatter_vars # Pass frontmatter vars as already provided
118
+ )
119
+ # Merge: frontmatter > template defaults
120
+ variables = {**template_vars, **frontmatter_vars}
121
+ if variables:
122
+ print(f"Variables loaded: {len(variables)}")
123
+ except Exception as e:
124
+ print(f"Warning: Could not load variables: {e}")
125
+ variables = frontmatter_vars
126
+ else:
127
+ variables = frontmatter_vars
128
+
129
+ print()
130
+
131
+ try:
132
+ convert_md_to_docx(
133
+ input_path=args.input,
134
+ output_path=args.output,
135
+ template_path=args.template_path,
136
+ template_name=template_name,
137
+ templates_dir=args.templates_dir,
138
+ document_name=args.document_name,
139
+ document_title=args.document_title,
140
+ font_name=args.font,
141
+ fonts_dir=args.fonts_dir,
142
+ diagram_width=args.diagram_width,
143
+ diagram_scale=args.diagram_scale,
144
+ diagram_format=args.diagram_format,
145
+ embed_svg_in_word=args.embed_svg_in_word,
146
+ debug=args.debug,
147
+ variables=variables,
148
+ embed_fonts=not args.no_embed_fonts,
149
+ update_fields=args.update_fields,
150
+ enable_code_render=not getattr(args, 'no_code_render', False),
151
+ enable_tree_render=not getattr(args, 'no_tree_render', False),
152
+ code_theme=getattr(args, 'code_theme', None),
153
+ code_line_numbers=getattr(args, 'code_line_numbers', False)
154
+ )
155
+
156
+ # Save manifest to both locations with template name
157
+ if template_name:
158
+ features = {'variables': bool(variables)}
159
+ save_manifest_to_both_locations(
160
+ source_path=input_path,
161
+ output_path=output_path,
162
+ template_name=template_name,
163
+ features=features
164
+ )
165
+
166
+ print(f"Conversion successful!")
167
+ print(f" Output saved to: {args.output}")
168
+ if template_name:
169
+ manifest_path = output_path.parent / f"{output_path.stem}_manifest.xml"
170
+ print(f" Manifest saved to: {manifest_path}")
171
+ if args.debug:
172
+ debug_path = Path(args.output).with_name(f"{Path(args.output).stem}_debug.md")
173
+ print(f" Debug markdown saved to: {debug_path}")
174
+ return 0
175
+ except Exception as e:
176
+ print(f"Conversion failed: {e}", file=sys.stderr)
177
+ return 1
178
+
179
+
180
+ def cmd_extract(args: argparse.Namespace) -> int:
181
+ """Handle the extract command (DOCX to MD)."""
182
+ from .docx_reader import convert_docx_to_md
183
+
184
+ input_path = Path(args.input)
185
+ if not input_path.exists():
186
+ print(f"Error: Input file not found: {args.input}", file=sys.stderr)
187
+ return 1
188
+
189
+ print(f"Extracting: {args.input}")
190
+ print(f"Output: {args.output}")
191
+ if args.include_meta:
192
+ print("Including metadata file")
193
+ print()
194
+
195
+ try:
196
+ result = convert_docx_to_md(
197
+ input_path=input_path,
198
+ output_path=Path(args.output),
199
+ include_meta=args.include_meta,
200
+ extract_images=True
201
+ )
202
+ print(f"Extraction successful!")
203
+ print(f" Markdown saved to: {args.output}")
204
+ if args.include_meta:
205
+ meta_path = Path(args.output).parent / f"{Path(args.output).stem}_meta.xml"
206
+ print(f" Metadata saved to: {meta_path}")
207
+ if result.images:
208
+ images_dir = Path(args.output).parent / f"{Path(args.output).stem}_images"
209
+ print(f" Images extracted to: {images_dir}/")
210
+ return 0
211
+ except Exception as e:
212
+ print(f"Extraction failed: {e}", file=sys.stderr)
213
+ return 1
214
+
215
+
216
+ def cmd_merge(args: argparse.Namespace) -> int:
217
+ """Handle the merge command (round-trip editing)."""
218
+ from .round_trip import merge_md_to_docx
219
+
220
+ original = Path(args.original)
221
+ edited = Path(args.edited)
222
+
223
+ if not original.exists():
224
+ print(f"Error: Original DOCX not found: {args.original}", file=sys.stderr)
225
+ return 1
226
+ if not edited.exists():
227
+ print(f"Error: Edited Markdown not found: {args.edited}", file=sys.stderr)
228
+ return 1
229
+
230
+ print(f"Merging: {args.edited} into {args.original}")
231
+ print(f"Output: {args.output}")
232
+ print()
233
+
234
+ try:
235
+ result = merge_md_to_docx(
236
+ original_docx=original,
237
+ edited_md=edited,
238
+ output_path=Path(args.output),
239
+ meta_path=Path(args.meta) if args.meta else None
240
+ )
241
+ print(f"Merge successful!")
242
+ print(f" Output saved to: {args.output}")
243
+ print(f" Changes applied: {len(result.changes_applied)}")
244
+ if result.warnings:
245
+ print(" Warnings:")
246
+ for warning in result.warnings:
247
+ print(f" - {warning}")
248
+ return 0
249
+ except Exception as e:
250
+ print(f"Merge failed: {e}", file=sys.stderr)
251
+ return 1
252
+
253
+
254
+ def cmd_create_template(args: argparse.Namespace) -> int:
255
+ """Handle the create-template command."""
256
+ from .template_extractor import create_template
257
+
258
+ source = Path(args.source)
259
+ if not source.exists():
260
+ print(f"Error: Source file not found: {args.source}", file=sys.stderr)
261
+ return 1
262
+
263
+ print(f"Creating template from: {args.source}")
264
+ print(f"Template name: {args.name}")
265
+ if args.templates_dir:
266
+ print(f"Templates directory: {args.templates_dir}")
267
+ if args.no_cover_page:
268
+ print("Cover page: disabled")
269
+ elif args.cover_boundary:
270
+ print(f"Cover page boundary: paragraph {args.cover_boundary}")
271
+ print()
272
+
273
+ # Parse cover boundary if provided
274
+ cover_boundary = None
275
+ if args.cover_boundary:
276
+ try:
277
+ cover_boundary = int(args.cover_boundary) - 1 # Convert to 0-based
278
+ except ValueError:
279
+ print(f"Error: Invalid cover boundary: {args.cover_boundary}", file=sys.stderr)
280
+ return 1
281
+
282
+ try:
283
+ template_path = create_template(
284
+ source_docx=source,
285
+ template_name=args.name,
286
+ templates_dir=Path(args.templates_dir) if args.templates_dir else None,
287
+ interactive=not args.non_interactive,
288
+ include_cover_page=not args.no_cover_page,
289
+ cover_boundary=cover_boundary
290
+ )
291
+ print(f"\nTemplate created successfully!")
292
+ print(f" Location: {template_path}/")
293
+ return 0
294
+ except Exception as e:
295
+ print(f"Template creation failed: {e}", file=sys.stderr)
296
+ return 1
297
+
298
+
299
+ def cmd_analyze(args: argparse.Namespace) -> int:
300
+ """Handle the analyze command (analyze DOCX for template variables)."""
301
+ from .template_extractor import analyze_document_for_variables
302
+
303
+ input_path = Path(args.input)
304
+
305
+ if not input_path.exists():
306
+ print(f"Error: Input file not found: {args.input}", file=sys.stderr)
307
+ return 1
308
+
309
+ print(f"Analyzing: {args.input}")
310
+ print()
311
+
312
+ try:
313
+ analysis = analyze_document_for_variables(input_path)
314
+
315
+ if args.json:
316
+ import json
317
+ result = {
318
+ 'source_file': analysis.source_file,
319
+ 'paragraph_count': analysis.paragraph_count,
320
+ 'has_cover_page': analysis.has_cover_page,
321
+ 'cover_boundary': analysis.cover_boundary,
322
+ 'has_different_first_page_header': analysis.has_different_first_page_header,
323
+ 'candidates': [
324
+ {
325
+ 'id': c.id,
326
+ 'category': c.category,
327
+ 'category_label': c.category_label,
328
+ 'content': c.content,
329
+ 'suggested_name': c.suggested_name,
330
+ 'description': c.description,
331
+ }
332
+ for c in analysis.candidates
333
+ ]
334
+ }
335
+ print(json.dumps(result, indent=2, ensure_ascii=False))
336
+ else:
337
+ analysis.print_summary()
338
+
339
+ # Print additional info
340
+ print(f"\nDocument Info:")
341
+ print(f" Paragraphs: {analysis.paragraph_count}")
342
+ print(f" Cover page detected: {'Yes' if analysis.has_cover_page else 'No'}")
343
+ if analysis.cover_boundary is not None:
344
+ print(f" Cover boundary: paragraph {analysis.cover_boundary + 1}")
345
+ print(f" Different first page header: {'Yes' if analysis.has_different_first_page_header else 'No'}")
346
+ print(f" Variable candidates: {len(analysis.candidates)}")
347
+
348
+ return 0
349
+
350
+ except Exception as e:
351
+ print(f"Error analyzing document: {e}", file=sys.stderr)
352
+ return 1
353
+
354
+
355
+ def cmd_list_templates(args: argparse.Namespace) -> int:
356
+ """Handle the list-templates command."""
357
+ from .template_manager import list_templates
358
+
359
+ templates = list_templates(
360
+ templates_dir=Path(args.templates_dir) if args.templates_dir else None
361
+ )
362
+
363
+ if not templates:
364
+ print("No templates found.")
365
+ if not args.templates_dir:
366
+ print(" (Looking in ./templates/)")
367
+ else:
368
+ print(f" (Looking in {args.templates_dir}/)")
369
+ return 0
370
+
371
+ print("Available templates:")
372
+ print()
373
+ for template in templates:
374
+ name = template['name']
375
+ desc = template.get('description', '')
376
+ has_vars = template.get('has_variables', False)
377
+ var_indicator = " [has variables]" if has_vars else ""
378
+
379
+ print(f" {name}{var_indicator}")
380
+ if desc:
381
+ print(f" {desc}")
382
+
383
+ return 0
384
+
385
+
386
+ def cmd_convert_pdf(args: argparse.Namespace) -> int:
387
+ """Handle the convert-pdf command."""
388
+ from .pdf_converter import (
389
+ convert_to_pdf,
390
+ batch_convert_to_pdf,
391
+ PDFConversionError
392
+ )
393
+ from .pdf_server import PDFServerError
394
+
395
+ # Collect input files
396
+ input_files = []
397
+
398
+ for pattern in args.inputs:
399
+ # Check if it's a glob pattern
400
+ if '*' in pattern or '?' in pattern:
401
+ matches = glob.glob(pattern, recursive=True)
402
+ input_files.extend(Path(m) for m in matches)
403
+ else:
404
+ input_files.append(Path(pattern))
405
+
406
+ if not input_files:
407
+ print("Error: No input files found.", file=sys.stderr)
408
+ return 1
409
+
410
+ # Validate all input files exist
411
+ missing = [f for f in input_files if not f.exists()]
412
+ if missing:
413
+ for f in missing:
414
+ print(f"Error: File not found: {f}", file=sys.stderr)
415
+ return 1
416
+
417
+ # Determine if batch mode
418
+ is_batch = len(input_files) > 1 or args.output_dir
419
+
420
+ # Build options
421
+ pdf_format = args.pdf_format or 'pdf'
422
+ page_size = args.page_size or 'a4'
423
+ keep_docx = not args.no_keep_docx
424
+
425
+ try:
426
+ if is_batch:
427
+ # Batch conversion mode
428
+ output_dir = Path(args.output_dir) if args.output_dir else Path('.')
429
+
430
+ print(f"Batch converting {len(input_files)} file(s) to PDF...")
431
+ print(f"Output directory: {output_dir}")
432
+ print(f"PDF format: {pdf_format}")
433
+ print(f"Page size: {page_size}")
434
+ print(f"Keep intermediate DOCX: {'Yes' if keep_docx else 'No'}")
435
+ print()
436
+
437
+ # Build kwargs for MD/AsciiDoc conversion
438
+ kwargs = {}
439
+ if args.template:
440
+ kwargs['template_name'] = args.template
441
+ if args.templates_dir:
442
+ kwargs['templates_dir'] = args.templates_dir
443
+
444
+ result = batch_convert_to_pdf(
445
+ input_paths=input_files,
446
+ output_dir=output_dir,
447
+ keep_docx=keep_docx,
448
+ pdf_format=pdf_format,
449
+ page_size=page_size,
450
+ **kwargs
451
+ )
452
+
453
+ # Report results
454
+ print(f"Conversion complete!")
455
+ print(f" Successful: {result.success_count}/{result.total}")
456
+
457
+ if result.successful:
458
+ for pdf_path in result.successful:
459
+ print(f" - {pdf_path}")
460
+
461
+ if result.failed:
462
+ print(f" Failed: {result.failure_count}/{result.total}")
463
+ for input_path, error in result.failed.items():
464
+ print(f" - {input_path}: {error}")
465
+ return 1
466
+
467
+ return 0
468
+
469
+ else:
470
+ # Single file conversion
471
+ input_path = input_files[0]
472
+
473
+ # Determine output path
474
+ if args.output:
475
+ output_path = Path(args.output)
476
+ else:
477
+ output_path = input_path.with_suffix('.pdf')
478
+
479
+ print(f"Converting: {input_path}")
480
+ print(f"Output: {output_path}")
481
+ print(f"PDF format: {pdf_format}")
482
+ print(f"Page size: {page_size}")
483
+
484
+ ext = input_path.suffix.lower()
485
+ if ext != '.docx':
486
+ print(f"Keep intermediate DOCX: {'Yes' if keep_docx else 'No'}")
487
+
488
+ if args.template:
489
+ print(f"Template: {args.template}")
490
+ print()
491
+
492
+ # Build kwargs for MD/AsciiDoc conversion
493
+ kwargs = {}
494
+ if args.template:
495
+ kwargs['template_name'] = args.template
496
+ if args.templates_dir:
497
+ kwargs['templates_dir'] = args.templates_dir
498
+
499
+ docx_path = convert_to_pdf(
500
+ input_path=input_path,
501
+ output_path=output_path,
502
+ keep_docx=keep_docx,
503
+ pdf_format=pdf_format,
504
+ page_size=page_size,
505
+ **kwargs
506
+ )
507
+
508
+ print("Conversion successful!")
509
+ print(f" PDF saved to: {output_path}")
510
+ if docx_path:
511
+ print(f" DOCX saved to: {docx_path}")
512
+
513
+ return 0
514
+
515
+ except PDFServerError as e:
516
+ print(f"PDF Server Error: {e}", file=sys.stderr)
517
+ print(" Make sure Docker is installed and running.", file=sys.stderr)
518
+ return 1
519
+ except PDFConversionError as e:
520
+ print(f"Conversion Error: {e}", file=sys.stderr)
521
+ return 1
522
+ except Exception as e:
523
+ print(f"Error: {e}", file=sys.stderr)
524
+ return 1
525
+
526
+
527
+ def main():
528
+ """Main CLI entry point."""
529
+ parser = argparse.ArgumentParser(
530
+ description='Document Converter - Convert between Markdown and DOCX formats',
531
+ formatter_class=argparse.RawDescriptionHelpFormatter
532
+ )
533
+
534
+ subparsers = parser.add_subparsers(dest='command', help='Available commands')
535
+
536
+ # Convert command (MD to DOCX)
537
+ convert_parser = subparsers.add_parser(
538
+ 'convert',
539
+ help='Convert Markdown to DOCX',
540
+ formatter_class=argparse.RawDescriptionHelpFormatter,
541
+ epilog="""
542
+ Examples:
543
+ document-converter convert input.md output.docx
544
+ document-converter convert input.md output.docx --template-name corporate
545
+ document-converter convert input.md output.docx --document-name "Project X"
546
+ """
547
+ )
548
+ convert_parser.add_argument('input', type=str, help='Input Markdown file')
549
+ convert_parser.add_argument('output', type=str, help='Output DOCX file')
550
+ convert_parser.add_argument('--template-path', type=str, default=None,
551
+ help='Path to DOCX template file')
552
+ convert_parser.add_argument('--template-name', type=str, default=None,
553
+ help='Name of template from templates directory')
554
+ convert_parser.add_argument('--document-name', type=str, default=None,
555
+ help='Document name for template placeholder')
556
+ convert_parser.add_argument('--document-title', type=str, default=None,
557
+ help='Document title for template placeholder')
558
+ convert_parser.add_argument('--font', type=str, default='Source Sans Pro',
559
+ help='Default font name')
560
+ convert_parser.add_argument('--fonts-dir', type=str, default=None,
561
+ help='Path to fonts directory')
562
+ convert_parser.add_argument('--diagram-width', type=int, default=1200,
563
+ help='Maximum diagram width in pixels')
564
+ convert_parser.add_argument('--diagram-scale', type=int, default=2,
565
+ help='Diagram scale factor')
566
+ convert_parser.add_argument('--diagram-format', type=str, default='png',
567
+ choices=['png', 'svg', 'auto'],
568
+ help='Diagram output format (default: png). "auto" uses SVG for HTML/Markdown, PNG for DOCX.')
569
+ convert_parser.add_argument('--embed-svg-in-word', action='store_true',
570
+ help='[EXPERIMENTAL] Embed SVG directly in Word (requires Word 2016+). Only applies with --diagram-format svg.')
571
+ convert_parser.add_argument('--no-code-render', action='store_true',
572
+ help='Disable rendering code blocks as syntax-highlighted images')
573
+ convert_parser.add_argument('--no-tree-render', action='store_true',
574
+ help='Disable rendering ASCII trees as images')
575
+ convert_parser.add_argument('--code-theme', type=str, default=None,
576
+ help='Pygments theme for code highlighting (default: "default")')
577
+ convert_parser.add_argument('--code-line-numbers', action='store_true',
578
+ help='Show line numbers in code blocks')
579
+ convert_parser.add_argument('--debug', action='store_true',
580
+ help='Save debug markdown file')
581
+ convert_parser.add_argument('--non-interactive', action='store_true',
582
+ help='Use default values for missing template variables')
583
+ convert_parser.add_argument('--no-embed-fonts', action='store_true',
584
+ help='Do not embed fonts into the DOCX file (fonts embedded by default)')
585
+ convert_parser.add_argument('--ignore-frontmatter', action='store_true',
586
+ help='Ignore YAML frontmatter in source file')
587
+ convert_parser.add_argument('--language', type=str, default=None,
588
+ help='Language code for date formatting (e.g., en, hu, de, fr)')
589
+ # Field update options (mutually exclusive)
590
+ field_update_group = convert_parser.add_mutually_exclusive_group()
591
+ field_update_group.add_argument('--update-fields', action='store_true', dest='update_fields',
592
+ help='Update field codes (TOC, page numbers) after generation. Requires LibreOffice.')
593
+ field_update_group.add_argument('--no-update-fields', action='store_false', dest='update_fields',
594
+ help='Do not update field codes (default: auto-update when TOC is enabled)')
595
+ convert_parser.set_defaults(update_fields=None) # None = auto (update if TOC enabled)
596
+ add_common_args(convert_parser)
597
+
598
+ # Extract command (DOCX to MD)
599
+ extract_parser = subparsers.add_parser(
600
+ 'extract',
601
+ help='Extract Markdown from DOCX',
602
+ epilog="""
603
+ Examples:
604
+ document-converter extract document.docx output.md
605
+ document-converter extract document.docx output.md --include-meta
606
+ """
607
+ )
608
+ extract_parser.add_argument('input', type=str, help='Input DOCX file')
609
+ extract_parser.add_argument('output', type=str, help='Output Markdown file')
610
+ extract_parser.add_argument('--include-meta', action='store_true',
611
+ help='Generate metadata XML file for round-trip editing')
612
+ add_common_args(extract_parser)
613
+
614
+ # Merge command (round-trip)
615
+ merge_parser = subparsers.add_parser(
616
+ 'merge',
617
+ help='Merge edited Markdown back into DOCX',
618
+ epilog="""
619
+ Examples:
620
+ document-converter merge original.docx edited.md output.docx
621
+ """
622
+ )
623
+ merge_parser.add_argument('original', type=str, help='Original DOCX file')
624
+ merge_parser.add_argument('edited', type=str, help='Edited Markdown file')
625
+ merge_parser.add_argument('output', type=str, help='Output DOCX file')
626
+ merge_parser.add_argument('--meta', type=str, default=None,
627
+ help='Path to metadata file (auto-detected if not specified)')
628
+ add_common_args(merge_parser)
629
+
630
+ # Create-template command
631
+ template_parser = subparsers.add_parser(
632
+ 'create-template',
633
+ help='Create a template from an existing DOCX',
634
+ epilog="""
635
+ Examples:
636
+ document-converter create-template report.docx --name corporate-report
637
+ document-converter create-template report.docx --name corporate --templates-dir /shared/templates
638
+ """
639
+ )
640
+ template_parser.add_argument('source', type=str, help='Source DOCX file')
641
+ template_parser.add_argument('--name', type=str, required=True,
642
+ help='Name for the template')
643
+ template_parser.add_argument('--non-interactive', action='store_true',
644
+ help='Skip interactive variable selection')
645
+ template_parser.add_argument('--no-cover-page', action='store_true',
646
+ help='Do not include cover page in template')
647
+ template_parser.add_argument('--cover-boundary', type=str, default=None,
648
+ help='Paragraph number where cover page ends (e.g., "5")')
649
+ add_common_args(template_parser)
650
+
651
+ # Analyze command
652
+ analyze_parser = subparsers.add_parser(
653
+ 'analyze',
654
+ help='Analyze DOCX for potential template variables',
655
+ epilog="""
656
+ Examples:
657
+ document-converter analyze proposal.docx
658
+ document-converter analyze proposal.docx --json
659
+ """
660
+ )
661
+ analyze_parser.add_argument('input', type=str, help='Input DOCX file to analyze')
662
+ analyze_parser.add_argument('--json', action='store_true',
663
+ help='Output results as JSON')
664
+
665
+ # List-templates command
666
+ list_parser = subparsers.add_parser(
667
+ 'list-templates',
668
+ help='List available templates'
669
+ )
670
+ add_common_args(list_parser)
671
+
672
+ # Convert-pdf command
673
+ pdf_parser = subparsers.add_parser(
674
+ 'convert-pdf',
675
+ help='Convert documents to PDF',
676
+ formatter_class=argparse.RawDescriptionHelpFormatter,
677
+ epilog="""
678
+ Examples:
679
+ # Single file conversion
680
+ document-converter convert-pdf input.docx output.pdf
681
+ document-converter convert-pdf input.md output.pdf
682
+ document-converter convert-pdf input.adoc output.pdf
683
+
684
+ # With options
685
+ document-converter convert-pdf input.docx output.pdf --pdf-format pdf/a
686
+ document-converter convert-pdf input.md output.pdf --page-size letter
687
+
688
+ # Batch conversion
689
+ document-converter convert-pdf "*.docx" --output-dir ./pdfs
690
+ document-converter convert-pdf file1.md file2.adoc --output-dir ./pdfs
691
+
692
+ # With template for Markdown/AsciiDoc
693
+ document-converter convert-pdf input.md output.pdf --template corporate
694
+ """
695
+ )
696
+ pdf_parser.add_argument('inputs', nargs='+',
697
+ help='Input file(s) or glob pattern (e.g., "*.docx")')
698
+ pdf_parser.add_argument('output', nargs='?', default=None,
699
+ help='Output PDF file (for single file conversion)')
700
+ pdf_parser.add_argument('--output-dir', type=str, default=None,
701
+ help='Output directory for batch conversion')
702
+ pdf_parser.add_argument('--pdf-format', type=str, choices=['pdf', 'pdf/a'],
703
+ default='pdf', help='PDF format (default: pdf)')
704
+ pdf_parser.add_argument('--page-size', type=str, choices=['a4', 'letter', 'legal', 'a3', 'a5'],
705
+ default='a4', help='Page size (default: a4)')
706
+ pdf_parser.add_argument('--no-keep-docx', action='store_true',
707
+ help='Delete intermediate DOCX file after conversion')
708
+ pdf_parser.add_argument('--template', type=str, default=None,
709
+ help='Template name for Markdown/AsciiDoc conversion')
710
+ pdf_parser.add_argument('--diagram-format', type=str, default='png',
711
+ choices=['png', 'svg', 'auto'],
712
+ help='Diagram output format (default: png)')
713
+ add_common_args(pdf_parser)
714
+
715
+ # Parse arguments
716
+ args = parser.parse_args()
717
+
718
+ # Handle no command (backward compatibility - treat as convert)
719
+ if args.command is None:
720
+ # Check if old-style positional args were provided
721
+ if len(sys.argv) > 1 and not sys.argv[1].startswith('-'):
722
+ # Backward compatibility: treat as convert command
723
+ print("Note: Using legacy syntax. Consider using 'document-converter convert' instead.")
724
+ # Re-parse with convert command
725
+ sys.argv.insert(1, 'convert')
726
+ args = parser.parse_args()
727
+ else:
728
+ parser.print_help()
729
+ return 0
730
+
731
+ # Dispatch to command handler
732
+ handlers = {
733
+ 'convert': cmd_convert,
734
+ 'extract': cmd_extract,
735
+ 'merge': cmd_merge,
736
+ 'create-template': cmd_create_template,
737
+ 'analyze': cmd_analyze,
738
+ 'list-templates': cmd_list_templates,
739
+ 'convert-pdf': cmd_convert_pdf,
740
+ }
741
+
742
+ handler = handlers.get(args.command)
743
+ if handler:
744
+ return handler(args)
745
+ else:
746
+ parser.print_help()
747
+ return 0
748
+
749
+
750
+ if __name__ == '__main__':
751
+ sys.exit(main())