@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,442 @@
1
+ #!/usr/bin/env -S uv run --quiet
2
+ # /// script
3
+ # requires-python = ">=3.11"
4
+ # dependencies = []
5
+ # ///
6
+ """Auto-size markdown table columns and write `table_profiles:` frontmatter.
7
+
8
+ See `../SKILL.md` for the full description. Language-agnostic, heuristic,
9
+ re-runnable.
10
+
11
+ Usage:
12
+ profile.py PATH [PATH ...] [--apply] [--dry-run]
13
+ [--percentile N] [--min-ratio R]
14
+ [--max-ratio R] [--language CODE]
15
+ [--profile-prefix STR] [--verbose]
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import hashlib
21
+ import math
22
+ import re
23
+ import sys
24
+ from dataclasses import dataclass
25
+ from pathlib import Path
26
+ from typing import Iterable, Sequence
27
+
28
+ # ---------------------------------------------------------------------------
29
+ # Markdown table parsing
30
+ # ---------------------------------------------------------------------------
31
+
32
+ ROW_RE = re.compile(r"^\s*\|(.+)\|\s*$")
33
+ SEP_RE = re.compile(r"^\s*\|(?:\s*:?-{3,}:?\s*\|)+\s*$")
34
+ FENCE_RE = re.compile(r"^```")
35
+ FM_DELIM_RE = re.compile(r"^---\s*$")
36
+
37
+ EMPHASIS_RE = re.compile(r"(\*\*|__|\*|_)(.+?)\1")
38
+ STRIP_TOKENS_RE = re.compile(r"<[^>]+>")
39
+ LINK_RE = re.compile(r"\[([^\]]+)\]\(([^)]+)\)")
40
+ CODE_SPAN_RE = re.compile(r"`([^`]+)`")
41
+ HTML_BR_RE = re.compile(r"<br\s*/?>", flags=re.I)
42
+ SENTINEL_CELLS = {"", "—", "-", "–", "n/a", "na", "tbd", "todo", "—.", "— "}
43
+
44
+
45
+ def split_cells(line: str) -> list[str]:
46
+ m = ROW_RE.match(line)
47
+ if not m:
48
+ return []
49
+ return [c.strip() for c in m.group(1).split("|")]
50
+
51
+
52
+ def strip_fm(text: str) -> tuple[str | None, str | None, str]:
53
+ """Return (opening_line, frontmatter_body, body) or (None, None, whole).
54
+
55
+ Keeps the original newline conventions intact.
56
+ """
57
+ lines = text.splitlines(keepends=True)
58
+ if not lines or not FM_DELIM_RE.match(lines[0].rstrip()):
59
+ return None, None, text
60
+ for i in range(1, len(lines)):
61
+ if FM_DELIM_RE.match(lines[i].rstrip()):
62
+ return lines[0], "".join(lines[1:i]), "".join(lines[i + 1:])
63
+ return None, None, text
64
+
65
+
66
+ @dataclass
67
+ class Table:
68
+ headers: list[str]
69
+ rows: list[list[str]]
70
+ line_no: int # 0-based header line
71
+
72
+ @property
73
+ def n_cols(self) -> int:
74
+ return len(self.headers)
75
+
76
+
77
+ def find_tables(body_text: str) -> list[Table]:
78
+ """Locate every pipe table in body text, ignoring fenced code blocks."""
79
+ lines = body_text.splitlines()
80
+ out: list[Table] = []
81
+ in_fence = False
82
+ i = 0
83
+ n = len(lines)
84
+ while i < n:
85
+ line = lines[i]
86
+ # Toggle code fence state on `^```` lines (track to skip tables inside code blocks)
87
+ if FENCE_RE.match(line):
88
+ in_fence = not in_fence
89
+ i += 1
90
+ continue
91
+ if in_fence:
92
+ i += 1
93
+ continue
94
+ header_cells = split_cells(line)
95
+ if len(header_cells) >= 2 and i + 1 < n and SEP_RE.match(lines[i + 1]):
96
+ headers = [c for c in header_cells] # keep original; blanks become empty
97
+ # Drop leading/trailing empty cells introduced by leading/trailing pipes
98
+ if headers and headers[0] == "":
99
+ headers = headers[1:]
100
+ if headers and headers[-1] == "":
101
+ headers = headers[:-1]
102
+ n_cols = len(headers)
103
+ if n_cols < 2:
104
+ i += 1
105
+ continue
106
+ rows: list[list[str]] = []
107
+ j = i + 2
108
+ while j < n:
109
+ ln = lines[j]
110
+ if not ROW_RE.match(ln):
111
+ break
112
+ cells = split_cells(ln)
113
+ # same leading/trailing trim
114
+ if cells and cells[0] == "":
115
+ cells = cells[1:]
116
+ if cells and cells[-1] == "":
117
+ cells = cells[:-1]
118
+ if len(cells) != n_cols:
119
+ # forgiving: pad or truncate
120
+ if len(cells) < n_cols:
121
+ cells = cells + [""] * (n_cols - len(cells))
122
+ else:
123
+ cells = cells[:n_cols]
124
+ rows.append(cells)
125
+ j += 1
126
+ out.append(Table(headers=headers, rows=rows, line_no=i))
127
+ i = j
128
+ else:
129
+ i += 1
130
+ return out
131
+
132
+
133
+ # ---------------------------------------------------------------------------
134
+ # Width measurement
135
+ # ---------------------------------------------------------------------------
136
+
137
+
138
+ def normalise_text(cell: str) -> str:
139
+ """Strip markdown syntax that doesn't contribute to visual width."""
140
+ text = HTML_BR_RE.sub("\n", cell)
141
+ # links → keep anchor text, URL handled separately as unbreakable token
142
+ text = LINK_RE.sub(lambda m: m.group(1), text)
143
+ # emphasis
144
+ for _ in range(3):
145
+ new = EMPHASIS_RE.sub(lambda m: m.group(2), text)
146
+ if new == text:
147
+ break
148
+ text = new
149
+ # raw HTML tags
150
+ text = STRIP_TOKENS_RE.sub("", text)
151
+ return text
152
+
153
+
154
+ def unbreakable_tokens(cell: str) -> Iterable[str]:
155
+ """Yield tokens that will not word-wrap — code spans, long unbroken words, URLs."""
156
+ for m in CODE_SPAN_RE.finditer(cell):
157
+ yield m.group(1)
158
+ for m in LINK_RE.finditer(cell):
159
+ yield m.group(2) # the URL itself is unbreakable
160
+ cleaned = normalise_text(cell)
161
+ for token in re.split(r"\s+", cleaned):
162
+ if not token:
163
+ continue
164
+ # Split on whitespace for "word" boundaries. Hyphens are soft breaks
165
+ # in PDF renderers, so we DO split on them here (matches LibreOffice
166
+ # behaviour) — otherwise Q-NEW-1 looks unbreakable when in practice
167
+ # it wraps at dashes.
168
+ for sub in re.split(r"[-–—]", token):
169
+ if sub:
170
+ yield sub
171
+
172
+
173
+ def percentile(values: Sequence[int], p: float) -> float:
174
+ if not values:
175
+ return 0.0
176
+ vs = sorted(values)
177
+ if len(vs) == 1:
178
+ return vs[0]
179
+ k = (len(vs) - 1) * (p / 100.0)
180
+ lo = math.floor(k)
181
+ hi = math.ceil(k)
182
+ if lo == hi:
183
+ return float(vs[lo])
184
+ return vs[lo] + (vs[hi] - vs[lo]) * (k - lo)
185
+
186
+
187
+ def col_natural_width(header: str, cells: Sequence[str], percentile_p: int) -> dict:
188
+ """Compute a natural-width score for a single column."""
189
+ header_text = normalise_text(header)
190
+ header_len = max(len(header_text), 3) # no column shorter than ~3 chars
191
+ cell_lens: list[int] = []
192
+ max_token = 0
193
+ for c in cells:
194
+ if not c:
195
+ continue
196
+ if c.strip().lower() in SENTINEL_CELLS:
197
+ continue
198
+ cleaned = normalise_text(c)
199
+ # split multi-line cells on explicit breaks, take the longest
200
+ parts = [p for p in cleaned.split("\n") if p.strip()]
201
+ line_len = max((len(p) for p in parts), default=0)
202
+ cell_lens.append(line_len)
203
+ for tok in unbreakable_tokens(c):
204
+ if len(tok) > max_token:
205
+ max_token = len(tok)
206
+
207
+ p_len = percentile(cell_lens, percentile_p) if cell_lens else header_len
208
+ max_cell = max(cell_lens) if cell_lens else header_len
209
+ # natural width = max of:
210
+ # - header length
211
+ # - p-percentile of cell lengths
212
+ # - longest unbreakable token (cells with code/URL stay readable)
213
+ natural = max(header_len, p_len, max_token)
214
+ return {
215
+ "header": header,
216
+ "header_len": header_len,
217
+ "max": max_cell,
218
+ "p": p_len,
219
+ "tok": max_token,
220
+ "natural": natural,
221
+ }
222
+
223
+
224
+ # ---------------------------------------------------------------------------
225
+ # Profile computation
226
+ # ---------------------------------------------------------------------------
227
+
228
+
229
+ def compute_widths(
230
+ naturals: list[float],
231
+ min_ratio: float,
232
+ max_ratio: float,
233
+ smoothing: str,
234
+ ) -> list[float]:
235
+ """Map natural widths to relative multipliers.
236
+
237
+ Smoothing modes:
238
+ - linear: raw widths (strongest differentiation, extremes dominate)
239
+ - sqrt: square-root smoothing (balanced, default)
240
+ - log: log1p smoothing (gentle, columns stay close to 1.0)
241
+ """
242
+ if smoothing == "linear":
243
+ smoothed = [max(float(v), 1.0) for v in naturals]
244
+ elif smoothing == "log":
245
+ smoothed = [math.log1p(v) for v in naturals]
246
+ else: # sqrt (default)
247
+ smoothed = [math.sqrt(max(float(v), 1.0)) for v in naturals]
248
+
249
+ mean = sum(smoothed) / len(smoothed)
250
+ if mean <= 0:
251
+ return [1.0] * len(naturals)
252
+ raw = [s / mean for s in smoothed]
253
+ clamped = [min(max(r, min_ratio), max_ratio) for r in raw]
254
+ return [round(r, 2) for r in clamped]
255
+
256
+
257
+ def profile_id(prefix: str, headers: Sequence[str], language: str | None) -> str:
258
+ key = "\x1f".join(h.strip() for h in headers).encode("utf-8")
259
+ digest = hashlib.blake2b(key, digest_size=4).hexdigest() # 8 hex chars
260
+ parts = [prefix, digest]
261
+ if language:
262
+ parts.append(language)
263
+ return "_".join(parts)
264
+
265
+
266
+ def format_profiles_block(profiles: dict[str, tuple[list[str], list[float]]]) -> str:
267
+ lines = ["table_profiles:"]
268
+ for pid, (cols, widths) in profiles.items():
269
+ lines.append(f" {pid}:")
270
+ lines.append(f" columns: {list(cols)!r}")
271
+ lines.append(f" widths: {widths!r}")
272
+ return "\n".join(lines)
273
+
274
+
275
+ def strip_existing_profiles_block(fm_body: str) -> str:
276
+ """Remove any existing `table_profiles:` block from frontmatter body."""
277
+ out: list[str] = []
278
+ skipping = False
279
+ for line in fm_body.splitlines():
280
+ if skipping:
281
+ if line.startswith(" ") or line.strip() == "":
282
+ continue
283
+ skipping = False
284
+ if line.startswith("table_profiles:"):
285
+ skipping = True
286
+ continue
287
+ out.append(line)
288
+ # trim trailing empties
289
+ while out and out[-1].strip() == "":
290
+ out.pop()
291
+ return "\n".join(out) + "\n"
292
+
293
+
294
+ def detect_language_hint(path: Path) -> str | None:
295
+ stem = path.stem
296
+ if stem.endswith(".hu"):
297
+ return "hu"
298
+ if stem.endswith(".en"):
299
+ return "en"
300
+ return None
301
+
302
+
303
+ # ---------------------------------------------------------------------------
304
+ # Per-file processing
305
+ # ---------------------------------------------------------------------------
306
+
307
+
308
+ @dataclass
309
+ class FileReport:
310
+ path: Path
311
+ tables: list[tuple[Table, str, list[float], list[dict]]] # (table, pid, widths, col_stats)
312
+ wrote: bool
313
+ skipped_reason: str | None = None
314
+
315
+
316
+ def process_file(
317
+ path: Path,
318
+ percentile_p: int,
319
+ min_ratio: float,
320
+ max_ratio: float,
321
+ smoothing: str,
322
+ profile_prefix: str,
323
+ language_override: str | None,
324
+ apply: bool,
325
+ ) -> FileReport:
326
+ text = path.read_text(encoding="utf-8")
327
+ fm_open, fm_body, body = strip_fm(text)
328
+ if fm_body is None:
329
+ return FileReport(path=path, tables=[], wrote=False, skipped_reason="no frontmatter")
330
+
331
+ tables = find_tables(body)
332
+ if not tables:
333
+ return FileReport(path=path, tables=[], wrote=False, skipped_reason="no tables")
334
+
335
+ lang = language_override or detect_language_hint(path)
336
+
337
+ profiles: dict[str, tuple[list[str], list[float]]] = {}
338
+ report_tables: list[tuple[Table, str, list[float], list[dict]]] = []
339
+ for t in tables:
340
+ col_stats = [
341
+ col_natural_width(h, [r[i] for r in t.rows], percentile_p)
342
+ for i, h in enumerate(t.headers)
343
+ ]
344
+ widths = compute_widths(
345
+ [cs["natural"] for cs in col_stats],
346
+ min_ratio,
347
+ max_ratio,
348
+ smoothing,
349
+ )
350
+ pid = profile_id(profile_prefix, t.headers, lang)
351
+ profiles[pid] = (list(t.headers), widths)
352
+ report_tables.append((t, pid, widths, col_stats))
353
+
354
+ if apply:
355
+ new_fm = strip_existing_profiles_block(fm_body)
356
+ new_fm = new_fm.rstrip() + "\n\n" + format_profiles_block(profiles) + "\n"
357
+ path.write_text(fm_open + new_fm + "---\n" + body, encoding="utf-8")
358
+ return FileReport(path=path, tables=report_tables, wrote=True)
359
+
360
+ return FileReport(path=path, tables=report_tables, wrote=False)
361
+
362
+
363
+ # ---------------------------------------------------------------------------
364
+ # CLI
365
+ # ---------------------------------------------------------------------------
366
+
367
+
368
+ def iter_markdown_files(arg: Path) -> Iterable[Path]:
369
+ if arg.is_dir():
370
+ yield from (p for p in arg.rglob("*.md") if p.is_file())
371
+ elif arg.is_file():
372
+ yield arg
373
+
374
+
375
+ def main(argv: list[str]) -> int:
376
+ p = argparse.ArgumentParser(description="Auto-size markdown table columns.")
377
+ p.add_argument("paths", nargs="+", type=Path, help="markdown files or directories")
378
+ p.add_argument("--apply", action="store_true")
379
+ p.add_argument("--dry-run", action="store_true", help="default; no changes")
380
+ p.add_argument("--percentile", type=int, default=75,
381
+ help="cell-length percentile used as column's natural width (default 75)")
382
+ p.add_argument("--smoothing", choices=["linear", "sqrt", "log"], default="sqrt",
383
+ help="width-normalisation curve (default sqrt)")
384
+ p.add_argument("--min-ratio", type=float, default=0.3)
385
+ p.add_argument("--max-ratio", type=float, default=3.5)
386
+ p.add_argument("--page-chars", type=int, default=95, help="unused currently, kept for compat")
387
+ p.add_argument("--language", default=None, help="override language suffix")
388
+ p.add_argument("--profile-prefix", default="tbl")
389
+ p.add_argument("--verbose", action="store_true")
390
+ args = p.parse_args(argv)
391
+
392
+ files: list[Path] = []
393
+ for arg in args.paths:
394
+ files.extend(iter_markdown_files(arg))
395
+
396
+ total_files = 0
397
+ total_tables = 0
398
+ total_wrote = 0
399
+
400
+ for f in sorted(files):
401
+ rep = process_file(
402
+ f,
403
+ percentile_p=args.percentile,
404
+ min_ratio=args.min_ratio,
405
+ max_ratio=args.max_ratio,
406
+ smoothing=args.smoothing,
407
+ profile_prefix=args.profile_prefix,
408
+ language_override=args.language,
409
+ apply=args.apply,
410
+ )
411
+ if rep.skipped_reason:
412
+ if args.verbose:
413
+ print(f"[skip] {f}: {rep.skipped_reason}", file=sys.stderr)
414
+ continue
415
+ total_files += 1
416
+ total_tables += len(rep.tables)
417
+ if rep.wrote:
418
+ total_wrote += 1
419
+ mark = "write" if rep.wrote else "dry-run"
420
+ print(f"[{mark}] {f} ({len(rep.tables)} table(s))")
421
+ for t, pid, widths, stats in rep.tables:
422
+ print(f" • {pid} cols={t.n_cols} widths={widths}")
423
+ if args.verbose:
424
+ for cs, w in zip(stats, widths):
425
+ print(
426
+ f" {cs['header']!r:<30} "
427
+ f"hdr={cs['header_len']:3d} max={cs['max']:3d} "
428
+ f"p{args.percentile}={int(cs['p']):3d} "
429
+ f"tok={cs['tok']:3d} → {w:.2f}"
430
+ )
431
+
432
+ print(
433
+ f"\nProcessed {total_files} file(s), {total_tables} table(s), "
434
+ f"wrote {total_wrote} file(s)."
435
+ )
436
+ if not args.apply:
437
+ print("Re-run with --apply to write the frontmatter.")
438
+ return 0
439
+
440
+
441
+ if __name__ == "__main__":
442
+ raise SystemExit(main(sys.argv[1:]))
@@ -0,0 +1,59 @@
1
+ # Nano-banana Mermaid render styles (document-conversion skill)
2
+ #
3
+ # Named visual styles for rendering Mermaid diagrams as nano-banana (Gemini)
4
+ # images instead of mmdc. Reference one from a Markdown file's frontmatter:
5
+ #
6
+ # nano_banana:
7
+ # enabled: true
8
+ # style: ros-3d # name below, or omit to use `default`
9
+ #
10
+ # `style` may also be an inline prompt string instead of a name.
11
+ #
12
+ # Each style provides:
13
+ # description : human note (ignored by the renderer)
14
+ # prompt : positive STYLE BLOCK appended after the diagram description
15
+ # negative : NEGATIVE list (what to avoid)
16
+ # model : default nano-banana model for this style
17
+ # background : white | transparent (white embeds cleanly in DOCX/PDF pages)
18
+ # width : generation hint passed to the model prompt
19
+
20
+ default: ros-3d
21
+
22
+ styles:
23
+ # ROS / Zenit pptx look — photorealistic 3D glossy blocks.
24
+ # Adapted from Projektek/Zenit/IKEA/Brand_Palette_Style.md §4.7
25
+ # (white background variant for document embedding).
26
+ ros-3d:
27
+ description: "ROS pptx 3D diagram blocks (navy/steel/orange glossy cuboids)"
28
+ model: gemini-3-pro-image
29
+ background: white
30
+ width: 1600
31
+ prompt: |
32
+ STYLE: photorealistic 3D render of glossy rounded blocks / cuboids with soft
33
+ realistic shadows, depth and cinematic studio lighting, modern enterprise look.
34
+ Blocks in deep navy #1F3A5F, steel-blue #4472C4 and orange #F47A20 with subtle
35
+ reflective tops and bevelled edges; connector arrows as sleek glossy 3D tubes;
36
+ small glossy orange numbered spheres for sequence steps. Crisp, perfectly
37
+ legible white or navy sans-serif labels spelled EXACTLY as written in the
38
+ diagram source, with correct accents. Clean flat WHITE (#FFFFFF) background,
39
+ objects evenly lit and well spaced. Wide composition with generous margins.
40
+ negative: |
41
+ no flat vector, no 2D, no cartoon, no neon, no watermark, no logo, no extra
42
+ or duplicated or garbled text, no misspellings, no checkerboard, no clutter.
43
+
44
+ # Clean flat-design alternative.
45
+ flat:
46
+ description: "Clean flat enterprise diagram (no 3D)"
47
+ model: gemini-3-pro-image
48
+ background: white
49
+ width: 1600
50
+ prompt: |
51
+ STYLE: clean modern flat-design diagram, rounded rectangle nodes with thin
52
+ borders, soft drop shadows, a restrained enterprise palette of navy #1F3A5F,
53
+ steel-blue #4472C4 and a single orange #F47A20 accent on a flat WHITE
54
+ background. Thin straight connector arrows. Crisp, perfectly legible
55
+ sans-serif labels spelled EXACTLY as written in the diagram source. Balanced
56
+ layout with generous whitespace.
57
+ negative: |
58
+ no 3D render, no photorealism, no gradients-heavy look, no neon, no watermark,
59
+ no logo, no extra or garbled text, no misspellings, no clutter.
@@ -0,0 +1,109 @@
1
+ """Engine-internal unit tests: styled-diagram md5 cache + mmdc fallback.
2
+
3
+ These cover logic that lives below the TS↔engine JSON boundary (the TS suite
4
+ mocks the boundary and cannot reach it). Pure stdlib + monkeypatch; no docling,
5
+ no Docker. Run:
6
+
7
+ python -m pytest packages/document-converter/engine/tests -q
8
+ """
9
+ import hashlib
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ import pytest
14
+
15
+ ENGINE_DIR = Path(__file__).resolve().parent.parent
16
+ sys.path.insert(0, str(ENGINE_DIR))
17
+
18
+ import engine_cli # noqa: E402
19
+
20
+ MERMAID_DOC = "intro\n\n```mermaid\ngraph TD; A-->B\n```\n\noutro\n"
21
+
22
+
23
+ def _write_md(tmp_path: Path) -> Path:
24
+ md = tmp_path / "doc.md"
25
+ md.write_text(MERMAID_DOC, encoding="utf-8")
26
+ return md
27
+
28
+
29
+ def test_cache_hit_skips_generation(tmp_path, monkeypatch):
30
+ md = _write_md(tmp_path)
31
+ cache = tmp_path / ".mermaid-cache"
32
+ cache.mkdir()
33
+ # Pre-seed the cache with the exact md5 key.
34
+ digest = hashlib.md5("graph TD; A-->B".encode()).hexdigest()
35
+ (cache / f"{digest}.png").write_bytes(b"PNG")
36
+
37
+ calls = {"nano": 0, "mmdc": 0}
38
+ monkeypatch.setattr(engine_cli, "_nano_banana", lambda *a, **k: calls.__setitem__("nano", calls["nano"] + 1) or True)
39
+ monkeypatch.setattr(engine_cli, "_mmdc", lambda *a, **k: calls.__setitem__("mmdc", calls["mmdc"] + 1))
40
+
41
+ out = engine_cli._render_styled_diagrams(md, "ros-3d", cache)
42
+
43
+ assert calls == {"nano": 0, "mmdc": 0} # cache hit -> neither called
44
+ text = out.read_text(encoding="utf-8")
45
+ assert f"{digest}.png" in text
46
+ assert "```mermaid" not in text
47
+
48
+
49
+ def test_cache_miss_generates_via_nano_banana(tmp_path, monkeypatch):
50
+ md = _write_md(tmp_path)
51
+ cache = tmp_path / ".mermaid-cache"
52
+ monkeypatch.setenv("GEMINI_API_KEY", "k")
53
+
54
+ def fake_nano(source, style, png):
55
+ png.write_bytes(b"PNG")
56
+ return True
57
+
58
+ calls = {"mmdc": 0}
59
+ monkeypatch.setattr(engine_cli, "_nano_banana", fake_nano)
60
+ monkeypatch.setattr(engine_cli, "_mmdc", lambda *a, **k: calls.__setitem__("mmdc", calls["mmdc"] + 1))
61
+
62
+ engine_cli._render_styled_diagrams(md, "ros-3d", cache)
63
+ assert calls["mmdc"] == 0 # nano-banana succeeded; no fallback
64
+
65
+
66
+ def test_falls_back_to_mmdc_when_nano_fails(tmp_path, monkeypatch):
67
+ md = _write_md(tmp_path)
68
+ cache = tmp_path / ".mermaid-cache"
69
+ monkeypatch.setenv("GEMINI_API_KEY", "k")
70
+
71
+ monkeypatch.setattr(engine_cli, "_nano_banana", lambda *a, **k: False)
72
+
73
+ def fake_mmdc(source, png):
74
+ png.write_bytes(b"PNG")
75
+
76
+ fallback = {"n": 0}
77
+ monkeypatch.setattr(engine_cli, "_mmdc", lambda s, p: (fallback.__setitem__("n", fallback["n"] + 1), fake_mmdc(s, p)))
78
+
79
+ engine_cli._render_styled_diagrams(md, "ros-3d", cache)
80
+ assert fallback["n"] == 1 # fell back to mmdc exactly once
81
+
82
+
83
+ def test_missing_key_uses_mmdc(tmp_path, monkeypatch):
84
+ md = _write_md(tmp_path)
85
+ cache = tmp_path / ".mermaid-cache"
86
+ monkeypatch.delenv("GEMINI_API_KEY", raising=False)
87
+
88
+ nano = {"n": 0}
89
+ monkeypatch.setattr(engine_cli, "_nano_banana", lambda *a, **k: nano.__setitem__("n", nano["n"] + 1) or True)
90
+ monkeypatch.setattr(engine_cli, "_mmdc", lambda s, p: p.write_bytes(b"PNG"))
91
+
92
+ engine_cli._render_styled_diagrams(md, "ros-3d", cache)
93
+ assert nano["n"] == 0 # no key -> nano-banana never attempted, mmdc used
94
+
95
+
96
+ def test_unknown_command_envelope():
97
+ import io
98
+ import json
99
+
100
+ monkey_stdin = io.StringIO(json.dumps({"command": "nope"}))
101
+ out = io.StringIO()
102
+ old_in, old_out = sys.stdin, sys.stdout
103
+ sys.stdin, sys.stdout = monkey_stdin, out
104
+ try:
105
+ rc = engine_cli.main()
106
+ finally:
107
+ sys.stdin, sys.stdout = old_in, old_out
108
+ assert rc == 2
109
+ assert json.loads(out.getvalue())["error"]["code"] == "UNKNOWN_COMMAND"
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@blackbelt-technology/pi-dashboard-document-converter",
3
+ "version": "0.5.4",
4
+ "description": "TypeScript facade over a Dockerized Python document engine (pi-doc-engine). Bidirectional: ingest any format to provenance-stamped Markdown for kb, produce templated DOCX/PDF with diagrams. Engine quarantined in Docker; TS is the only call surface.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "publishConfig": { "access": "public" },
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/BlackBeltTechnology/pi-agent-dashboard",
11
+ "directory": "packages/document-converter"
12
+ },
13
+ "pi": {
14
+ "skills": [".pi/skills/document-converter"]
15
+ },
16
+ "exports": {
17
+ ".": "./src/index.ts",
18
+ "./schema": "./src/schema.ts"
19
+ },
20
+ "engines": {
21
+ "node": ">=22.5.0"
22
+ },
23
+ "scripts": {
24
+ "build:image": "./engine/build-image.sh",
25
+ "test": "vitest run"
26
+ },
27
+ "dependencies": {
28
+ "@blackbelt-technology/pi-dashboard-shared": "^0.5.4"
29
+ },
30
+ "files": ["dist", "src", "engine", ".pi/skills/"],
31
+ "keywords": ["pi-package", "pi-skill", "document-conversion", "docling", "docx", "pdf", "markdown", "ocr", "kb", "pi"]
32
+ }