@blackbelt-technology/pi-dashboard-document-converter 0.5.4 → 0.6.1

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.
@@ -0,0 +1,124 @@
1
+ ---
2
+ name: doc-summarizer
3
+ description: >-
4
+ Summarize documents of any size by extracting them with the document-converter
5
+ engine, chunking to fit context, and fanning chunks out to subagents that
6
+ produce structured summaries, then synthesizing one unified summary. Handles
7
+ PDF, DOCX, PPTX, XLSX, HTML, CSV, TXT, MD and more. Use when the user wants to:
8
+ (1) summarize a single document, (2) summarize multiple documents in batch,
9
+ (3) condense content from large files that exceed context limits, (4) get a
10
+ quick overview of document contents. Triggers on: "summarize this document",
11
+ "what's in this PDF", "give me a summary of these files", "extract key points
12
+ from", "condense this document", "TL;DR of this file".
13
+ ---
14
+
15
+ # Document Summarizer
16
+
17
+ Summarize documents of any size. Extraction goes through the **document-converter
18
+ engine facade** (`dc.convertToMarkdown`) — the same Docker-quarantined engine the
19
+ `document-converter` skill uses. There are NO host-side extractor scripts here;
20
+ the facade is the only extraction surface. Chunking and synthesis are agent work.
21
+
22
+ ## Prerequisites
23
+
24
+ - The `document-converter` package built and runnable: Docker available, image
25
+ built (`cd packages/document-converter && npm run build:image`). See the
26
+ `document-converter` SKILL for the full facade contract.
27
+ - Nothing else. No `pdftotext`/`pandoc`/Python on the host — the engine owns all
28
+ format handling inside Docker.
29
+
30
+ ## Step 1 — Extract to Markdown via the engine
31
+
32
+ Call the facade; never invoke Python, docling, or pdftotext directly.
33
+
34
+ ```ts
35
+ import { createDocumentConverter } from "@blackbelt-technology/pi-dashboard-document-converter";
36
+ const dc = createDocumentConverter({ image: "pi-doc-engine:0.1.0", stagingDir: "/abs/staging" });
37
+
38
+ const { output } = await dc.convertToMarkdown("<file_path>"); // digital PDF/DOCX/…
39
+ // scanned PDF: pass OCR explicitly
40
+ await dc.convertToMarkdown("<file_path>", { ocr: { mode: "force", lang: ["english"] } });
41
+ ```
42
+
43
+ The result is a provenance-stamped `.md` in `stagingDir`. Read that file to get
44
+ the document text. On failure the call rejects with `DocConverterError`
45
+ (`.code`, `.stderr`) — surface `UNSUPPORTED_FORMAT`, `OCR_LANG_UNSUPPORTED`,
46
+ `INGEST_FAILED`, `DOCKER_UNAVAILABLE` rather than retrying blindly.
47
+
48
+ ## Step 2 — Decide direct vs. chunked
49
+
50
+ Measure the extracted Markdown:
51
+
52
+ - **< ~8,000 words (~10k tokens):** summarize directly in the current context
53
+ (Step 3a).
54
+ - **>= ~8,000 words:** chunk and fan out (Step 3b).
55
+
56
+ ## Step 3a — Direct summarization (small documents)
57
+
58
+ Read the extracted `.md` and produce a summary using the [output format](#summary-output-format)
59
+ below: title/subject, key points, entities, document type, language.
60
+
61
+ ## Step 3b — Chunked summarization (large documents)
62
+
63
+ 1. **Chunk.** Split the extracted Markdown into context-friendly pieces
64
+ (~3,000–4,000 tokens each). Prefer natural boundaries — headings, sections,
65
+ page markers in the engine output — over blind character cuts. No script
66
+ needed; split with judgment.
67
+ 2. **Fan out.** For each chunk launch a subagent (`Agent` tool,
68
+ `subagent_type: "general-purpose"`), up to ~3–4 concurrent:
69
+
70
+ ```
71
+ Summarize this text chunk (chunk {i}/{total} of document '{filename}').
72
+ Extract: key points, entities (people/orgs/dates/amounts), topics, and any
73
+ conclusions or action items. Output as structured markdown.
74
+
75
+ Text:
76
+ {chunk_text}
77
+ ```
78
+ 3. **Merge.** Collect chunk summaries, deduplicate entities and key points, and
79
+ produce one unified summary in the [output format](#summary-output-format). If
80
+ the merged result is still > ~8,000 words, run one more summarization pass on
81
+ it.
82
+
83
+ ## Batch summarization
84
+
85
+ For a directory or glob: extract each file via `dc.convertToMarkdown` (run a few
86
+ in parallel), then apply the single-document workflow per file. Emit a table:
87
+
88
+ ```markdown
89
+ | # | File | Type | Language | Words | Key Topics | Summary |
90
+ |---|------|------|----------|-------|------------|---------|
91
+ | 1 | invoice.pdf | Invoice | EN | 450 | AcmeCorp, 2024Q4 | Quarterly invoice… |
92
+ ```
93
+
94
+ ## Summary output format
95
+
96
+ ```markdown
97
+ ## Summary: {document_name}
98
+
99
+ **Type**: {document_type}
100
+ **Language**: {language}
101
+ **Word Count**: {word_count}
102
+ **Date**: {detected_date or file_modified_date}
103
+
104
+ ### Key Points
105
+ - Point 1
106
+ - Point 2
107
+
108
+ ### Entities
109
+ - **People**: …
110
+ - **Organizations**: …
111
+ - **Dates**: …
112
+ - **Amounts**: …
113
+
114
+ ### Brief Summary
115
+ {2-3 paragraph narrative summary}
116
+ ```
117
+
118
+ ## Special cases
119
+
120
+ - **Scanned PDF, no text:** the engine returns little/empty text on `mode: auto`.
121
+ Re-run with `ocr: { mode: "force", lang: [...] }` (canonical language names).
122
+ - **Encrypted / unsupported / empty:** surface the `DocConverterError.code` and
123
+ `.stderr`; report metadata only.
124
+ - **Mixed-language:** report the primary language, note others present.
@@ -265,14 +265,18 @@ if __name__ == "__main__":
265
265
  def _convert_with_local_libreoffice(
266
266
  docx_path: Path,
267
267
  output_path: Path,
268
- libreoffice_path: str
268
+ libreoffice_path: str,
269
+ export_filter: str = 'writer_pdf_Export'
269
270
  ) -> None:
270
- """Convert DOCX to PDF using local LibreOffice.
271
+ """Convert a document to PDF using local LibreOffice.
271
272
 
272
273
  Args:
273
- docx_path: Path to input DOCX file.
274
+ docx_path: Path to input document (DOCX or, with `impress_pdf_Export`,
275
+ PPTX).
274
276
  output_path: Path to output PDF file.
275
277
  libreoffice_path: Path to LibreOffice soffice binary.
278
+ export_filter: LibreOffice PDF export filter. `writer_pdf_Export` for
279
+ Writer docs (default); `impress_pdf_Export` for Impress decks.
276
280
 
277
281
  Raises:
278
282
  PDFConversionError: If conversion fails.
@@ -282,13 +286,14 @@ def _convert_with_local_libreoffice(
282
286
  output_dir = output_path.parent
283
287
  output_dir.mkdir(parents=True, exist_ok=True)
284
288
 
285
- # Run LibreOffice in headless mode with font embedding
286
- # Use writer_pdf_Export filter with EmbedStandardFonts option
289
+ # Run LibreOffice in headless mode with font embedding. The export filter
290
+ # is chosen by document type (Writer vs Impress); EmbedStandardFonts is a
291
+ # shared PDF-export option.
287
292
  result = subprocess.run(
288
293
  [
289
294
  libreoffice_path,
290
295
  '--headless',
291
- '--convert-to', 'pdf:writer_pdf_Export:{"EmbedStandardFonts":{"type":"boolean","value":"true"}}',
296
+ '--convert-to', f'pdf:{export_filter}:{{"EmbedStandardFonts":{{"type":"boolean","value":"true"}}}}',
292
297
  '--outdir', str(output_dir),
293
298
  str(docx_path)
294
299
  ],
@@ -662,6 +667,10 @@ def convert_to_pdf(
662
667
  )
663
668
  return None
664
669
 
670
+ elif ext == '.pptx':
671
+ convert_pptx_to_pdf(input_path, output_path)
672
+ return None
673
+
665
674
  elif ext in ('.md', '.markdown'):
666
675
  return convert_md_to_pdf(
667
676
  input_path,
@@ -685,10 +694,50 @@ def convert_to_pdf(
685
694
  else:
686
695
  raise ValueError(
687
696
  f"Cannot detect format for file: {input_path}. "
688
- "Supported extensions: .docx, .md, .markdown, .adoc, .asciidoc, .asc"
697
+ "Supported extensions: .docx, .pptx, .md, .markdown, .adoc, .asciidoc, .asc"
689
698
  )
690
699
 
691
700
 
701
+ def convert_pptx_to_pdf(
702
+ input_path: Union[str, Path],
703
+ output_path: Union[str, Path],
704
+ ) -> None:
705
+ """Convert a PPTX deck to PDF.
706
+
707
+ Uses local LibreOffice with the Impress export filter (faithful slide
708
+ layout, fonts, charts). Falls back to the Docker/Gotenberg LibreOffice route
709
+ when no local soffice is present.
710
+
711
+ Args:
712
+ input_path: Path to input PPTX file.
713
+ output_path: Path to output PDF file.
714
+
715
+ Raises:
716
+ FileNotFoundError: If input file does not exist.
717
+ PDFServerError: If Docker/server is not available and no local LibreOffice.
718
+ PDFConversionError: If conversion fails.
719
+ """
720
+ input_path = Path(input_path)
721
+ output_path = Path(output_path)
722
+
723
+ if not input_path.exists():
724
+ raise FileNotFoundError(f"Input file does not exist: {input_path}")
725
+
726
+ libreoffice_path = find_local_libreoffice()
727
+ if libreoffice_path:
728
+ _convert_with_local_libreoffice(
729
+ input_path, output_path, libreoffice_path, export_filter='impress_pdf_Export'
730
+ )
731
+ return
732
+
733
+ # Fall back to Docker/Gotenberg (its LibreOffice route handles pptx too).
734
+ server = get_server()
735
+ base_url = server.ensure_running()
736
+ pdf_bytes = _send_conversion_request(input_path, base_url)
737
+ output_path.parent.mkdir(parents=True, exist_ok=True)
738
+ output_path.write_bytes(pdf_bytes)
739
+
740
+
692
741
  def batch_convert_to_pdf(
693
742
  input_paths: List[Union[str, Path]],
694
743
  output_dir: Union[str, Path],
package/package.json CHANGED
@@ -1,17 +1,22 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-dashboard-document-converter",
3
- "version": "0.5.4",
3
+ "version": "0.6.1",
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
5
  "type": "module",
6
6
  "license": "MIT",
7
- "publishConfig": { "access": "public" },
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
8
10
  "repository": {
9
11
  "type": "git",
10
12
  "url": "https://github.com/BlackBeltTechnology/pi-agent-dashboard",
11
13
  "directory": "packages/document-converter"
12
14
  },
13
15
  "pi": {
14
- "skills": [".pi/skills/document-converter"]
16
+ "skills": [
17
+ ".pi/skills/document-converter",
18
+ ".pi/skills/doc-summarizer"
19
+ ]
15
20
  },
16
21
  "exports": {
17
22
  ".": "./src/index.ts",
@@ -25,8 +30,24 @@
25
30
  "test": "vitest run"
26
31
  },
27
32
  "dependencies": {
28
- "@blackbelt-technology/pi-dashboard-shared": "^0.5.4"
33
+ "@blackbelt-technology/pi-dashboard-shared": "^0.6.1"
29
34
  },
30
- "files": ["dist", "src", "engine", ".pi/skills/"],
31
- "keywords": ["pi-package", "pi-skill", "document-conversion", "docling", "docx", "pdf", "markdown", "ocr", "kb", "pi"]
35
+ "files": [
36
+ "dist",
37
+ "src",
38
+ "engine",
39
+ ".pi/skills/"
40
+ ],
41
+ "keywords": [
42
+ "pi-package",
43
+ "pi-skill",
44
+ "document-conversion",
45
+ "docling",
46
+ "docx",
47
+ "pdf",
48
+ "markdown",
49
+ "ocr",
50
+ "kb",
51
+ "pi"
52
+ ]
32
53
  }
package/src/AGENTS.md ADDED
@@ -0,0 +1,14 @@
1
+ # DOX — packages/document-converter/src
2
+
3
+ Files in this directory. One row per source file.
4
+
5
+ | File | Purpose |
6
+ |------|---------|
7
+ | `engine.ts` | Docker invocation layer. `runEngine(cfg, req)` spawns `docker run --rm -i <image>`, pipes JSON request stdin, reads JSON response stdout. Path-identical mounts (`-v dir:dir`). Maps exit codes + envelope to `DocConverterError`. Injectable `EngineRunner`. |
8
+ | `errors.ts` | `DocConverterError` class + `DocConverterErrorCode` union. Single error type facade rejects with. Codes: DOCKER_UNAVAILABLE, ENGINE_NONZERO, BAD_RESPONSE, INPUT_NOT_FOUND, OCR_*, UNSUPPORTED_FORMAT, INGEST/PRODUCE/FILL/PROFILE_FAILED, INTERNAL. |
9
+ | `index.ts` | Facade entry. `createDocumentConverter(config)` returns object with convertToMarkdown, renderDocx, renderPdf, extractForEdit, mergeBack, fillFrontmatter, profileTables. Only call surface. Re-exports errors, types, schema, ocr, routing, provenance. `renderPdf` input widened to accept `.pptx` (engine `convert_to_pdf` routes pptx via LibreOffice Impress export filter) — no facade validation, engine-only change. See change: render-pptx-preview. |
10
+ | `ocr.ts` | Canonical language name→per-engine OCR code. `mapOcrCodes(langs, engine)`. EasyOCR `hu` vs Tesseract `hun`. rapidocr returns `[]`. Unsupported throws `OCR_LANG_UNSUPPORTED`. `SUPPORTED_LANGUAGES`. |
11
+ | `provenance.ts` | Provenance frontmatter writer. `sha256File`, `buildProvenance`, `provenanceFrontmatter`, `stampProvenance`. Stamps ingested `.md` with origin metadata. Byte-stable by hash. |
12
+ | `routing.ts` | Extension routing. `EXT_TO_DOCTYPE` map. `docTypeOf`, `isIngestable`, `ingestDocType`. Ingestable set = pdf/docx/pptx/xlsx. Throws `UNSUPPORTED_FORMAT`. |
13
+ | `schema.ts` | Unified document-frontmatter schema. Shared bus contract across stages. Types: `DocumentFrontmatter`, `Provenance`, `NanoBananaConfig`, `TableProfiles`, `TemplateVars`, `DocType`, `DiagramFormat`. Key consts. Mirrors `schema.json`. |
14
+ | `types.ts` | Facade option + result types. `OcrEngine`, `OcrMode`, `OcrOptions`, `ConvertToMarkdown*`, `RenderDocx/PdfOptions`, `Produce/Extract/MergeBack`, `FillFrontmatter/ProfileTablesOptions`. |
@@ -8,6 +8,7 @@
8
8
  * DOC_ENGINE_IMAGE=pi-doc-engine:0.1.0 built + loadable image tag
9
9
  * DOC_ENGINE_PDF=/abs/sample.pdf a digital PDF fixture (ingest case)
10
10
  * DOC_ENGINE_TEMPLATES=/abs/templates dir with <template>/template.docx (produce case)
11
+ * DOC_ENGINE_PPTX=/abs/deck.pptx a real .pptx deck (pptx→PDF case)
11
12
  * Never runs in the default `npm test`.
12
13
  *
13
14
  * DOC_ENGINE_IMAGE=pi-doc-engine:0.1.0 DOC_ENGINE_PDF=… DOC_ENGINE_TEMPLATES=… \
@@ -98,4 +99,24 @@ describe.skipIf(!ENABLED)("pi-doc-engine integration", () => {
98
99
  const bytes = await readFile(out);
99
100
  expect(bytes.byteLength).toBeGreaterThan(1000); // non-trivial DOCX
100
101
  }, 180_000);
102
+
103
+ it("produce: PPTX -> PDF via renderPdf (fidelity path; change: render-pptx-preview)", async () => {
104
+ // Verifies the engine input-type widening: renderPdf accepts .pptx and the
105
+ // LibreOffice Impress export filter produces a valid PDF. Point DOC_ENGINE_PPTX
106
+ // at a real deck.
107
+ const pptx = process.env.DOC_ENGINE_PPTX;
108
+ expect(pptx, "set DOC_ENGINE_PPTX to a sample .pptx deck").toBeTruthy();
109
+
110
+ const dc = createDocumentConverter({
111
+ image: IMAGE!,
112
+ stagingDir: join(work, "staging"),
113
+ mounts: [join(pptx!, "..")],
114
+ });
115
+ const out = join(work, "deck.pdf");
116
+ const res = await dc.renderPdf(pptx!, { output: out });
117
+ expect(res.output).toBe(out);
118
+ const bytes = await readFile(out);
119
+ expect(bytes.subarray(0, 5).toString()).toBe("%PDF-"); // valid PDF header
120
+ expect(bytes.byteLength).toBeGreaterThan(1000);
121
+ }, 180_000);
101
122
  });