Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(docparser): recover malformed PDFs with the builtin reader (#4716)
Baisheng Qian52e4cf8f8e07
diff --git a/internal/infrastructure/docparser/anydoc/anydoc.go b/internal/infrastructure/docparser/anydoc/anydoc.goindex 97b416e01..e66fbf4af 100644--- a/internal/infrastructure/docparser/anydoc/anydoc.go+++ b/internal/infrastructure/docparser/anydoc/anydoc.go@@ -226,6 +226,18 @@ func PDFNeedsOCR(err error) bool {strings.Contains(msg, "no extractable text")}+// PDFInvalidStructure reports a malformed document error that another PDF+// engine may still read. Encryption, resource limits and I/O errors are excluded.+func PDFInvalidStructure(err error) bool {+ if err == nil || errors.Is(err, ErrUnavailable) || errors.Is(err, ErrResourceLimit) {+ return false+ }+ if malformed, typed := backendPDFInvalidStructure(err); typed {+ return malformed+ }+ return strings.Contains(strings.ToLower(err.Error()), "invalid pdf structure")+}+func normalizeExt(s string) string {return strings.ToLower(strings.TrimPrefix(strings.TrimSpace(s), "."))}diff --git a/internal/infrastructure/docparser/anydoc/anydoc_test.go b/internal/infrastructure/docparser/anydoc/anydoc_test.goindex b54024e43..3f7389084 100644--- a/internal/infrastructure/docparser/anydoc/anydoc_test.go+++ b/internal/infrastructure/docparser/anydoc/anydoc_test.go@@ -2,10 +2,34 @@ package anydocimport ("errors"+ "fmt""slices""testing")+func TestPDFInvalidStructureLegacyErrors(t *testing.T) {+ for _, tc := range []struct {+ name string+ err error+ want bool+ }{+ {"nil", nil, false},+ {"legacy structure", errors.New("Invalid PDF structure"), true},+ {"wrapped structure", fmt.Errorf("convert: %w", errors.New("invalid PDF structure")), true},+ {"ocr", errors.New("no extractable text: OCR is required"), false},+ {"encrypted", errors.New("password required"), false},+ {"io", errors.New("failed to read input"), false},+ {"unavailable", fmt.Errorf("%w: invalid PDF structure", ErrUnavailable), false},+ {"resource limit", fmt.Errorf("%w: invalid PDF structure", ErrResourceLimit), false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if got := PDFInvalidStructure(tc.err); got != tc.want {+ t.Fatalf("PDFInvalidStructure(%v) = %v, want %v", tc.err, got, tc.want)+ }+ })+ }+}+func TestFormatForFileResolvesTypeAndName(t *testing.T) {cases := []struct {name stringdiff --git a/internal/infrastructure/docparser/anydoc/backend_cgo.go b/internal/infrastructure/docparser/anydoc/backend_cgo.goindex 775f6f42e..59de4c292 100644--- a/internal/infrastructure/docparser/anydoc/backend_cgo.go+++ b/internal/infrastructure/docparser/anydoc/backend_cgo.go@@ -3,6 +3,7 @@package anydocimport (+ "errors""fmt""strings"@@ -23,6 +24,14 @@ func backendUnavailableReason() string { return "" }func backendVersion() string { return upstream.Version }+func backendPDFInvalidStructure(err error) (malformed, typed bool) {+ var convertErr *upstream.ConvertError+ if !errors.As(err, &convertErr) {+ return false, false+ }+ return convertErr != nil && convertErr.Kind == "malformed", true+}+func backendConvert(data []byte, opts Options) (*Result, error) {format, err := upstreamFormat(opts.Format)if err != nil {diff --git a/internal/infrastructure/docparser/anydoc/backend_stub.go b/internal/infrastructure/docparser/anydoc/backend_stub.goindex 2f36ccae2..da9974ba2 100644--- a/internal/infrastructure/docparser/anydoc/backend_stub.go+++ b/internal/infrastructure/docparser/anydoc/backend_stub.go@@ -17,6 +17,8 @@ func backendUnavailableReason() string { return unavailableReason }func backendVersion() string { return "" }+func backendPDFInvalidStructure(_ error) (malformed, typed bool) { return false, false }+func backendConvert(_ []byte, _ Options) (*Result, error) {// Convert checks Available first, so this is only reachable if a caller// bypasses it.diff --git a/internal/infrastructure/docparser/anydoc/pdf_structure_linked_test.go b/internal/infrastructure/docparser/anydoc/pdf_structure_linked_test.gonew file mode 100644index 000000000..159c9e4e7--- /dev/null+++ b/internal/infrastructure/docparser/anydoc/pdf_structure_linked_test.go@@ -0,0 +1,26 @@+//go:build anydoc && cgo++package anydoc++import (+ "fmt"+ "testing"++ upstream "github.com/firecrawl/anydoc/go"+)++func TestPDFInvalidStructureTypedErrors(t *testing.T) {+ var absent *upstream.ConvertError+ if PDFInvalidStructure(absent) || PDFInvalidStructure(fmt.Errorf("convert: %w", absent)) {+ t.Fatal("typed nil must not trigger a fallback")+ }+ for _, kind := range []string{"malformed", "encrypted", "resource_limit", "io", "needs_ocr", "unsupported"} {+ t.Run(kind, func(t *testing.T) {+ // A typed rejection must take precedence over legacy error text.+ err := fmt.Errorf("convert: %w", &upstream.ConvertError{Kind: kind, Detail: "invalid PDF structure"})+ if got, want := PDFInvalidStructure(err), kind == "malformed"; got != want {+ t.Fatalf("PDFInvalidStructure(%v) = %v, want %v", err, got, want)+ }+ })+ }+}diff --git a/internal/infrastructure/docparser/anydoc_reader.go b/internal/infrastructure/docparser/anydoc_reader.goindex 8ae7bf01a..726cf7b60 100644--- a/internal/infrastructure/docparser/anydoc_reader.go+++ b/internal/infrastructure/docparser/anydoc_reader.go@@ -16,14 +16,13 @@ import (// the anydoc converter instead of the Python docreader service.//// Embedded images are rendered in place from the document model. PDFs with no-// text layer (scanned exam papers) cannot be converted by anydoc; when a-// fallback reader is configured (typically the builtin docreader) those files-// are handed off so pages can be rasterized for OCR.+// text layer or a structure anydoc rejects are handed to the configured+// fallback reader (typically the builtin docreader).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 has no extractable text. Nil means the+ // fallback is used when a PDF needs OCR or has an invalid structure. Nil means the// conversion error is returned to the caller.fallback interfaces.DocReader}@@ -52,8 +51,11 @@ func (r *AnydocReader) Read(ctx context.Context, req *types.ReadRequest) (*typesFormat: format,WithAssets: r.extractImages,})+ if format == "pdf" && anydoc.PDFInvalidStructure(err) {+ return r.readPDFFallback(ctx, req, err, "invalid_structure")+ }if format == "pdf" && (anydoc.PDFNeedsOCR(err) || pdfMarkdownIsEmpty(converted, err)) {- return r.readScannedPDF(ctx, req, err)+ return r.readPDFFallback(ctx, req, err, "scanned_pdf")}if err != nil {return nil, fmt.Errorf("anydoc conversion failed for %q: %w", req.FileName, err)@@ -81,7 +83,9 @@ func pdfMarkdownIsEmpty(converted *anydoc.Result, err error) bool {return strings.TrimSpace(converted.Markdown) == ""}-func (r *AnydocReader) readScannedPDF(ctx context.Context, req *types.ReadRequest, convertErr error) (*types.ReadResult, error) {+func (r *AnydocReader) readPDFFallback(+ ctx context.Context, req *types.ReadRequest, convertErr error, reason string,+) (*types.ReadResult, error) {if !r.canFallback() {if convertErr != nil {return nil, fmt.Errorf("anydoc conversion failed for %q: %w", req.FileName, convertErr)@@ -89,16 +93,15 @@ func (r *AnydocReader) readScannedPDF(ctx context.Context, req *types.ReadRequesreturn nil, fmt.Errorf("anydoc conversion failed for %q: PDF has no extractable text; OCR is required", req.FileName)}- logger.Infof(ctx, "[anydoc] %q contains pages requiring OCR, falling back to builtin for scanned-PDF OCR",- req.FileName)+ logger.Infof(ctx, "[anydoc] falling back to builtin for %q: %s", req.FileName, reason)fallbackReq := *reqfallbackReq.ParserEngine = BuiltinEngineNameresult, err := r.fallback.Read(ctx, &fallbackReq)if err != nil {- return nil, fmt.Errorf("anydoc scanned-PDF fallback failed for %q: %w", req.FileName, err)+ return nil, fmt.Errorf("anydoc PDF fallback (%s) failed for %q: %w", reason, req.FileName, err)}if result == nil {- return nil, fmt.Errorf("anydoc scanned-PDF fallback returned no result for %q", req.FileName)+ return nil, fmt.Errorf("anydoc PDF fallback (%s) returned no result for %q", reason, req.FileName)}if result.Metadata == nil {result.Metadata = map[string]string{}@@ -106,8 +109,8 @@ func (r *AnydocReader) readScannedPDF(ctx context.Context, req *types.ReadRequesif result.Metadata["parser"] == "" {result.Metadata["parser"] = BuiltinEngineName}- result.Metadata["anydoc_fallback"] = "scanned_pdf"- if result.Metadata["image_source_type"] == "" {+ result.Metadata["anydoc_fallback"] = reason+ if reason == "scanned_pdf" && result.Metadata["image_source_type"] == "" {result.Metadata["image_source_type"] = "scanned_pdf"}return result, nildiff --git a/internal/infrastructure/docparser/anydoc_reader_test.go b/internal/infrastructure/docparser/anydoc_reader_test.goindex d09bf4aeb..2753532ea 100644--- a/internal/infrastructure/docparser/anydoc_reader_test.go+++ b/internal/infrastructure/docparser/anydoc_reader_test.go@@ -8,6 +8,7 @@ import ("github.com/Tencent/WeKnora/internal/infrastructure/docparser/anydoc""github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/types/interfaces")func TestAnydocReaderRejectsUnsupportedFileType(t *testing.T) {@@ -78,10 +79,10 @@ func TestAnydocReaderFallsBackForScannedPDF(t *testing.T) {}},Metadata: map[string]string{"image_source_type": "scanned_pdf"},}}- result, err := NewAnydocReader(nil, fallback).readScannedPDF(context.Background(), &types.ReadRequest{+ result, err := NewAnydocReader(nil, fallback).readPDFFallback(context.Background(), &types.ReadRequest{FileName: "exam.pdf",FileType: "pdf",- }, errors.New("PDF has no extractable text (Scanned, 5 pages): OCR is required"))+ }, errors.New("PDF has no extractable text (Scanned, 5 pages): OCR is required"), "scanned_pdf")if err != nil {t.Fatalf("readScannedPDF: %v", err)}@@ -100,9 +101,9 @@ func TestAnydocReaderFallsBackForScannedPDF(t *testing.T) {}func TestAnydocReaderScannedPDFWithoutFallbackKeepsError(t *testing.T) {- _, err := NewAnydocReader(nil, nil).readScannedPDF(context.Background(), &types.ReadRequest{+ _, err := NewAnydocReader(nil, nil).readPDFFallback(context.Background(), &types.ReadRequest{FileName: "exam.pdf",- }, errors.New("PDF has no extractable text: OCR is required"))+ }, errors.New("PDF has no extractable text: OCR is required"), "scanned_pdf")if err == nil {t.Fatal("readScannedPDF succeeded without a fallback, want an error")}@@ -113,9 +114,9 @@ func TestAnydocReaderScannedPDFWithoutFallbackKeepsError(t *testing.T) {func TestAnydocReaderDisconnectedFallbackKeepsError(t *testing.T) {fallback := &disconnectedDocReader{}- _, err := NewAnydocReader(nil, fallback).readScannedPDF(context.Background(), &types.ReadRequest{+ _, err := NewAnydocReader(nil, fallback).readPDFFallback(context.Background(), &types.ReadRequest{FileName: "exam.pdf",- }, errors.New("PDF has no extractable text: OCR is required"))+ }, errors.New("PDF has no extractable text: OCR is required"), "scanned_pdf")if err == nil {t.Fatal("readScannedPDF succeeded with a disconnected fallback, want an error")}@@ -124,6 +125,93 @@ func TestAnydocReaderDisconnectedFallbackKeepsError(t *testing.T) {}}+func TestAnydocReaderStructureFallbackPreservesPageClassification(t *testing.T) {+ for _, source := range []string{"pdf_text_layer", "mixed_pdf", ""} {+ t.Run(source, func(t *testing.T) {+ fallback := &stubDocReader{result: &types.ReadResult{+ MarkdownContent: "recovered text",+ Metadata: map[string]string{"image_source_type": source},+ }}+ req := &types.ReadRequest{+ FileName: "report.pdf",+ FileType: "pdf",+ FileContent: []byte("original bytes"),+ ParserEngine: AnydocEngineName,+ }+ result, err := NewAnydocReader(nil, fallback).readPDFFallback(+ context.Background(), req, errors.New("invalid PDF structure"), "invalid_structure")+ if err != nil {+ t.Fatal(err)+ }+ if result.Metadata["image_source_type"] != source ||+ result.Metadata["anydoc_fallback"] != "invalid_structure" {+ t.Fatalf("fallback metadata = %#v", result.Metadata)+ }+ if req.ParserEngine != AnydocEngineName || fallback.got.ParserEngine != BuiltinEngineName ||+ string(fallback.got.FileContent) != string(req.FileContent) || fallback.got == req {+ t.Fatalf("fallback mutated caller request or lost original bytes: %#v", fallback.got)+ }+ })+ }+}++func TestAnydocReaderStructureFallbackFailures(t *testing.T) {+ original := errors.New("invalid PDF structure")+ for _, tc := range []struct {+ name string+ fallback interfaces.DocReader+ want string+ }{+ {"missing", nil, original.Error()},+ {"disconnected", &disconnectedDocReader{}, original.Error()},+ {"error", &stubDocReader{err: errors.New("builtin failed")}, "builtin failed"},+ {"nil result", &stubDocReader{}, "returned no result"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ _, err := NewAnydocReader(nil, tc.fallback).readPDFFallback(context.Background(),+ &types.ReadRequest{FileName: "report.pdf"}, original, "invalid_structure")+ if err == nil || !strings.Contains(err.Error(), tc.want) {+ t.Fatalf("fallback error = %v, want %q", err, tc.want)+ }+ if tc.fallback == nil && !errors.Is(err, original) {+ t.Fatalf("original conversion error was lost: %v", err)+ }+ })+ }+}++func TestAnydocReaderFallbackPreservesErrorClassification(t *testing.T) {+ for _, cause := range []error{context.Canceled, anydoc.ErrResourceLimit} {+ fallback := &stubDocReader{err: cause}+ _, err := NewAnydocReader(nil, fallback).readPDFFallback(context.Background(),+ &types.ReadRequest{FileName: "report.pdf"}, errors.New("invalid PDF structure"), "invalid_structure")+ if !errors.Is(err, cause) {+ t.Fatalf("fallback error = %v, want wrapped %v", err, cause)+ }+ }+}++func TestAnydocReaderReadFallsBackForMalformedPDF(t *testing.T) {+ if !anydoc.Available() {+ t.Skip("requires linked anydoc converter")+ }+ content := []byte("%PDF-1.7\n1 0 obj\n<< /Type /Catalog >>\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF\n")+ _, convertErr := anydoc.Convert(content, anydoc.Options{Format: "pdf"})+ if !anydoc.PDFInvalidStructure(convertErr) {+ t.Fatalf("fixture conversion error = %v, want malformed PDF", convertErr)+ }+ fallback := &stubDocReader{result: &types.ReadResult{MarkdownContent: "recovered"}}+ result, err := NewAnydocReader(nil, fallback).Read(context.Background(), &types.ReadRequest{+ FileName: "malformed.pdf", FileType: "pdf", FileContent: content,+ })+ if err != nil || result == nil || result.Metadata["anydoc_fallback"] != "invalid_structure" {+ t.Fatalf("Read() = %#v, %v", result, err)+ }+ if fallback.got == nil || string(fallback.got.FileContent) != string(content) {+ t.Fatal("Read did not hand the original PDF to the fallback")+ }+}+type stubDocReader struct {got *types.ReadRequestresult *types.ReadResult