Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(parser): route PPTX vector media through docreader (#4705)

Wang Xinming60ef4d77c4b0
diff --git a/internal/infrastructure/docparser/anydoc_pptx_vector_test.go b/internal/infrastructure/docparser/anydoc_pptx_vector_test.go
new file mode 100644
index 000000000..1c1f26ada
--- /dev/null
+++ b/internal/infrastructure/docparser/anydoc_pptx_vector_test.go
@@ -0,0 +1,163 @@
+package docparser
+
+import (
+ "archive/zip"
+ "bytes"
+ "context"
+ "errors"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+func presentationArchive(t *testing.T, names ...string) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ w := zip.NewWriter(&buf)
+ for _, name := range names {
+ f, err := w.Create(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.HasSuffix(name, "/") {
+ continue
+ }
+ if _, err := f.Write([]byte("synthetic media")); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := w.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return buf.Bytes()
+}
+
+func TestAnydocReaderRoutesPPTXVectorMedia(t *testing.T) {
+ for _, media := range []string{"ppt/media/chart.emf", "ppt/media/equation.wmf", "ppt/media/CHART.EMF"} {
+ t.Run(media, func(t *testing.T) {
+ req := &types.ReadRequest{
+ FileName: "slides.pptx", FileType: "pptx", ParserEngine: AnydocEngineName,
+ FileContent: presentationArchive(t, media),
+ Title: "Process diagram", RequestID: "vector-routing-regression",
+ ParserEngineOverrides: map[string]string{"parser_max_workers": "2"},
+ }
+ original := *req
+ want := &types.ReadResult{
+ MarkdownContent: "![chart](images/chart.png)",
+ ImageRefs: []types.ImageRef{{
+ Filename: "chart.png", OriginalRef: "images/chart.png", ImageData: []byte("png"),
+ }},
+ }
+ fallback := &stubDocReader{result: want}
+ got, err := NewAnydocReader(nil, fallback).Read(context.Background(), req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got != want || !reflect.DeepEqual(got.ImageRefs, want.ImageRefs) {
+ t.Fatalf("fallback result was not preserved: %+v", got)
+ }
+ if fallback.got == nil {
+ t.Fatal("vector presentation did not reach docreader")
+ }
+ expected := original
+ expected.ParserEngine = "markitdown"
+ if !reflect.DeepEqual(*fallback.got, expected) || !reflect.DeepEqual(*req, original) {
+ t.Fatal("fallback must change only its copied request's engine")
+ }
+ if got.Metadata["anydoc_fallback"] != "pptx_vector_media" || got.Metadata["parser"] != "markitdown" {
+ t.Fatalf("missing fallback metadata: %+v", got.Metadata)
+ }
+ })
+ }
+}
+
+func TestPPTXVectorMediaDetection(t *testing.T) {
+ if pptxHasVectorMedia([]byte("not a ZIP")) {
+ t.Fatal("invalid ZIP reported vector media")
+ }
+ if pptxHasVectorMedia(presentationArchive(t, "ppt/media/chart.emf/")) {
+ t.Fatal("directory reported as a vector image")
+ }
+}
+
+func TestAnydocReaderDoesNotRoutePPTMToMarkitdown(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ fileType string
+ fileName string
+ }{
+ {"explicit type", "pptm", "slides.pptm"},
+ {"explicit type takes precedence", "pptm", "slides.pptx"},
+ {"normalized explicit type", ".PPTM", "slides.pptm"},
+ {"inferred type", "", "slides.pptm"},
+ {"inferred uppercase type", "", "slides.PPTM"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ fallback := &stubDocReader{}
+ // The synthetic archive may fail native conversion, but PPTM must
+ // stay on anydoc: docreader does not support this file type.
+ _, _ = NewAnydocReader(nil, fallback).Read(context.Background(), &types.ReadRequest{
+ FileName: tc.fileName, FileType: tc.fileType,
+ FileContent: presentationArchive(t, "ppt/media/chart.emf"),
+ })
+ if fallback.got != nil {
+ t.Fatal("PPTM input incorrectly routed to MarkItDown")
+ }
+ })
+ }
+}
+
+func TestAnydocReaderPPTXVectorFallbackFailures(t *testing.T) {
+ sentinel := errors.New("docreader failed")
+ for _, tc := range []struct {
+ name string
+ reader *AnydocReader
+ want string
+ }{
+ {"missing", NewAnydocReader(nil, nil), "requires a connected docreader"},
+ {"disconnected", NewAnydocReader(nil, &disconnectedDocReader{}), "requires a connected docreader"},
+ {"error", NewAnydocReader(nil, &stubDocReader{err: sentinel}), "docreader failed"},
+ {"nil result", NewAnydocReader(nil, &stubDocReader{}), "returned no result"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ _, err := tc.reader.Read(context.Background(), &types.ReadRequest{
+ FileName: "slides.pptx", FileContent: presentationArchive(t, "ppt/media/chart.emf"),
+ })
+ if err == nil || !strings.Contains(err.Error(), tc.want) {
+ t.Fatalf("got %v, want %q", err, tc.want)
+ }
+ if tc.name == "error" && !errors.Is(err, sentinel) {
+ t.Fatal("fallback error lost its cause")
+ }
+ })
+ }
+}
+
+func TestAnydocReaderDoesNotRouteOtherInputsToMarkitdown(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ fileType string
+ media string
+ overrides map[string]string
+ }{
+ {"raster", "pptx", "ppt/media/chart.png", nil},
+ {"svg", "pptx", "ppt/media/chart.svg", nil},
+ {"unrelated directory", "pptx", "custom/chart.emf", nil},
+ {"word", "docx", "word/media/chart.emf", nil},
+ {"text only", "pptx", "ppt/media/chart.emf", map[string]string{"anydoc_extract_images": "false"}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ fallback := &stubDocReader{}
+ // Conversion may reject this directory-only synthetic archive. It
+ // must nevertheless never send these controls to MarkItDown.
+ _, _ = NewAnydocReader(tc.overrides, fallback).Read(context.Background(), &types.ReadRequest{
+ FileType: tc.fileType, FileContent: presentationArchive(t, tc.media),
+ })
+ if fallback.got != nil {
+ t.Fatal("non-vector or text-only input unexpectedly used fallback")
+ }
+ })
+ }
+}
diff --git a/internal/infrastructure/docparser/anydoc_reader.go b/internal/infrastructure/docparser/anydoc_reader.go
index 726cf7b60..e7950b10d 100644
--- a/internal/infrastructure/docparser/anydoc_reader.go
+++ b/internal/infrastructure/docparser/anydoc_reader.go
@@ -1,6 +1,8 @@
package docparser
import (
+ "archive/zip"
+ "bytes"
"context"
"fmt"
"path/filepath"
@@ -17,13 +19,14 @@ import (
//
// Embedded images are rendered in place from the document model. PDFs with no
// text layer or a structure anydoc rejects are handed to the configured
-// fallback reader (typically the builtin docreader).
+// fallback reader (typically the builtin docreader). PPTX files with EMF/WMF
+// media use the docreader's MarkItDown path to rasterize those embedded images.
type AnydocReader struct {
// extractImages controls whether embedded images are parsed and placed
// in the markdown. Off halves parse time for text-only indexing.
extractImages bool
- // fallback is used when a PDF needs OCR or has an invalid structure. Nil means the
- // conversion error is returned to the caller.
+ // fallback handles PDFs requiring OCR/structure recovery and PPTX vector
+ // media. Nil means the required conversion is reported as an error.
fallback interfaces.DocReader
}
@@ -46,6 +49,13 @@ func (r *AnydocReader) Read(ctx context.Context, req *types.ReadRequest) (*types
if !ok {
return nil, fmt.Errorf("anydoc engine does not support file type %q", fileTypeOf(req))
}
+ // Anydoc preserves vector bytes, but cannot rasterize EMF/WMF for the
+ // browser or VLM. MarkItDown's PPTX path already provides that conversion.
+ // Check the actual extension: anydoc also maps PPTM to its PPTX parser,
+ // but docreader does not support PPTM.
+ if r.extractImages && fileTypeOf(req) == "pptx" && pptxHasVectorMedia(req.FileContent) {
+ return r.readVectorPPTX(ctx, req)
+ }
converted, err := anydoc.Convert(req.FileContent, anydoc.Options{
Format: format,
@@ -76,6 +86,52 @@ func (r *AnydocReader) Read(ctx context.Context, req *types.ReadRequest) (*types
}, nil
}
+// Inspect only the ZIP directory: no media decompression or filesystem writes
+// are needed to decide which reader can preserve the presentation's images.
+func pptxHasVectorMedia(data []byte) bool {
+ archive, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
+ if err != nil {
+ return false // Let the converter report malformed input normally.
+ }
+ for _, file := range archive.File {
+ if file.FileInfo().IsDir() || !strings.HasPrefix(file.Name, "ppt/media/") {
+ continue
+ }
+ switch strings.ToLower(filepath.Ext(file.Name)) {
+ case ".emf", ".wmf":
+ return true
+ }
+ }
+ return false
+}
+
+func (r *AnydocReader) readVectorPPTX(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
+ if !r.canFallback() {
+ return nil, fmt.Errorf(
+ "anydoc conversion of %q with EMF/WMF images requires a connected docreader "+
+ "with MarkItDown and ImageMagick",
+ req.FileName)
+ }
+ logger.Infof(ctx, "[anydoc] %q contains EMF/WMF images, falling back to markitdown for rasterization", req.FileName)
+ fallbackReq := *req
+ fallbackReq.ParserEngine = "markitdown"
+ result, err := r.fallback.Read(ctx, &fallbackReq)
+ if err != nil {
+ return nil, fmt.Errorf("anydoc PPTX vector-media fallback failed for %q: %w", req.FileName, err)
+ }
+ if result == nil {
+ return nil, fmt.Errorf("anydoc PPTX vector-media fallback returned no result for %q", req.FileName)
+ }
+ if result.Metadata == nil {
+ result.Metadata = map[string]string{}
+ }
+ if result.Metadata["parser"] == "" {
+ result.Metadata["parser"] = "markitdown"
+ }
+ result.Metadata["anydoc_fallback"] = "pptx_vector_media"
+ return result, nil
+}
+
func pdfMarkdownIsEmpty(converted *anydoc.Result, err error) bool {
if err != nil || converted == nil {
return false
diff --git a/website-docs/02-architecture/03-document-pipeline.md b/website-docs/02-architecture/03-document-pipeline.md
index 0c3864dab..1c54e3836 100644
--- a/website-docs/02-architecture/03-document-pipeline.md
+++ b/website-docs/02-architecture/03-document-pipeline.md
@@ -271,7 +271,7 @@ Worker 消费 `TypeDocumentProcess` 后按五个规范化阶段推进,每个
4. `resolveDocReader` 返回 `interfaces.DocReader`:
- **builtin**:通过 gRPC(`docparser/grpc_parser.go`)或 HTTP(`http_parser.go`)调用 Python **docreader** 服务;
- **simple**:Go 原生解析 md/txt/csv/json/图片/音频(`builtin_converter.go`,CSV→Markdown 表格、JSON→递归分割的代码块,图片/音频转占位引用);
- - **anydoc**:Go 进程内解析 docx/doc/pptx/ppt/xlsx/xls/odf/rtf/epub/csv/pdf(`anydoc_reader.go`),底层是通过 cgo 链接的 anydoc Rust 库。office 文档的嵌入图按文档模型插回 Markdown 原位;无文字层的扫描件 PDF 在 DocReader 可用时回退到 builtin 整页渲染。链接了 anydoc 时,未配置规则的复杂格式默认走 anydoc,但 PDF 默认仍走 builtin。仅在带 `anydoc` 构建标签的二进制中可用,其余构建里该引擎在引擎列表中显示为不可用;
+ - **anydoc**:Go 进程内解析 docx/doc/pptx/ppt/xlsx/xls/odf/rtf/epub/csv/pdf(`anydoc_reader.go`),底层是通过 cgo 链接的 anydoc Rust 库。office 文档的嵌入图按文档模型插回 Markdown 原位;无文字层的扫描件 PDF 在 DocReader 可用时回退到 builtin 整页渲染。启用图片提取时,包含 `ppt/media/*.emf` 或 `*.wmf` 的 PPTX 会交给 DocReader 的 MarkItDown 路径,复用其 ImageMagick 光栅化能力;未连接 DocReader 时明确报错。普通位图 PPTX 和设置 `anydoc_extract_images=false` 的文件仍走 anydoc;此检测不覆盖旧版二进制 PPT。链接了 anydoc 时,未配置规则的复杂格式默认走 anydoc,但 PDF 默认仍走 builtin。仅在带 `anydoc` 构建标签的二进制中可用,其余构建里该引擎在引擎列表中显示为不可用;
- **weknoracloud / mineru / mineru_cloud / paddleocr_vl / paddleocr_vl_cloud**:HTTP 转换器(`engines.go` 注册,按 `mineru_endpoint`、`mineru_api_key`、`paddleocr_vl_endpoint` 等配置判定可用性;自建 `mineru` 会自动识别 MinerU 4.0 的 V1 API 与旧版 `/file_parse`,见[文档解析服务](../03-features/03-document-parsing.md#mineru-self-hosted))。
引擎目录集中在 `internal/infrastructure/docparser/engines.go`:每个引擎同时声明元数据(名称、描述、文件类型、可用性探针)与 `NewReader` 工厂,`docparser.NewReader` 按名字分发,未注册的名字(如只存在于 docreader 的 `markitdown`)落到 docreader 客户端。