fix(parser): default ppt/pptx to markitdown when no engine rules (#2882)
Empty parser_engine_rules used to resolve to builtin, which historically did not register ppt/pptx and failed with an unusable ValueError. Route those types to markitdown by default on both the Go resolver and the docreader registry, and list engines that actually support the type. Refs: https://github.com/Tencent/WeKnora/issues/2882main
parent
8db2e4f381
commit
52182385ec
|
|
@ -22,13 +22,22 @@ logger = logging.getLogger(__name__)
|
|||
|
||||
BUILTIN_ENGINE = "builtin"
|
||||
|
||||
# File types that builtin does not implement natively. When the requested
|
||||
# engine (including empty / builtin) cannot parse them, route to this engine
|
||||
# instead of raising ValueError — PPT/PPTX/CSV are markitdown-only.
|
||||
_DEFAULT_ENGINE_BY_TYPE = {
|
||||
"ppt": "markitdown",
|
||||
"pptx": "markitdown",
|
||||
"csv": "markitdown",
|
||||
}
|
||||
|
||||
|
||||
class ParserEngineRegistry:
|
||||
"""Registry for parser engines.
|
||||
|
||||
Each engine maps file extensions to parser classes.
|
||||
When a requested engine doesn't support a file type, the registry
|
||||
falls back to the builtin engine automatically.
|
||||
tries a type-level default engine, then builtin.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
|
|
@ -59,10 +68,12 @@ class ParserEngineRegistry:
|
|||
def get_parser_class(self, engine: str, file_type: str) -> Type[BaseParser]:
|
||||
"""Resolve parser class for the given engine and file type.
|
||||
|
||||
Falls back to builtin engine when the requested engine doesn't
|
||||
support the file type.
|
||||
Fallback order when the requested engine is empty or does not
|
||||
support the type: type-level default (e.g. ppt → markitdown),
|
||||
then builtin. Raises an actionable error listing engines that
|
||||
do support the type.
|
||||
"""
|
||||
ft = file_type.lower()
|
||||
ft = file_type.lower().lstrip(".")
|
||||
|
||||
if engine and engine in self._engines:
|
||||
cls = self._engines[engine].get(ft)
|
||||
|
|
@ -70,16 +81,36 @@ class ParserEngineRegistry:
|
|||
logger.info("Using engine '%s' for file type '%s'", engine, ft)
|
||||
return cls
|
||||
logger.info(
|
||||
"Engine '%s' does not support '%s', falling back to builtin",
|
||||
"Engine '%s' does not support '%s', falling back",
|
||||
engine,
|
||||
ft,
|
||||
)
|
||||
|
||||
default_engine = _DEFAULT_ENGINE_BY_TYPE.get(ft)
|
||||
if default_engine:
|
||||
cls = self._engines.get(default_engine, {}).get(ft)
|
||||
if cls:
|
||||
logger.info(
|
||||
"Using default engine '%s' for file type '%s'",
|
||||
default_engine,
|
||||
ft,
|
||||
)
|
||||
return cls
|
||||
|
||||
builtin = self._engines.get(BUILTIN_ENGINE, {})
|
||||
cls = builtin.get(ft)
|
||||
if cls:
|
||||
return cls
|
||||
|
||||
supported = sorted(
|
||||
name for name, parsers in self._engines.items() if ft in parsers
|
||||
)
|
||||
engine_label = engine or BUILTIN_ENGINE
|
||||
if supported:
|
||||
raise ValueError(
|
||||
f"Unsupported file type {file_type!r} for engine {engine_label!r}. "
|
||||
f"Configure one of: {', '.join(supported)}"
|
||||
)
|
||||
raise ValueError(f"Unsupported file type: {file_type}")
|
||||
|
||||
def list_engines(self, overrides: Optional[Dict[str, str]] = None) -> List[Dict]:
|
||||
|
|
|
|||
|
|
@ -3,7 +3,9 @@ import unittest
|
|||
from docreader.models.document import Document
|
||||
from docreader.parser.base_parser import BaseParser
|
||||
from docreader.parser.parser import Parser, detect_effective_file_type
|
||||
from docreader.parser.registry import BUILTIN_ENGINE, registry
|
||||
from docreader.parser.markitdown_parser import MarkitdownParser
|
||||
from docreader.parser.pdf_parser import PDFParser
|
||||
from docreader.parser.registry import BUILTIN_ENGINE, ParserEngineRegistry, registry
|
||||
from docreader.parser.xmind_parser import XMindParser
|
||||
|
||||
|
||||
|
|
@ -60,6 +62,44 @@ class ParserRoutingTest(unittest.TestCase):
|
|||
def test_unrelated_ole_type_is_not_reclassified(self):
|
||||
self.assertEqual("xls", detect_effective_file_type("xls", OLE_MAGIC))
|
||||
|
||||
def test_empty_engine_routes_pptx_to_markitdown(self):
|
||||
self.assertIs(registry.get_parser_class("", "pptx"), MarkitdownParser)
|
||||
self.assertIs(registry.get_parser_class("", "ppt"), MarkitdownParser)
|
||||
self.assertIs(registry.get_parser_class("", ".PPTX"), MarkitdownParser)
|
||||
|
||||
def test_builtin_engine_still_parses_pptx(self):
|
||||
self.assertIs(registry.get_parser_class(BUILTIN_ENGINE, "pptx"), MarkitdownParser)
|
||||
|
||||
def test_type_default_when_builtin_lacks_pptx(self):
|
||||
isolated = ParserEngineRegistry()
|
||||
isolated.register(BUILTIN_ENGINE, {"pdf": PDFParser})
|
||||
isolated.register(
|
||||
"markitdown",
|
||||
{"pptx": MarkitdownParser, "ppt": MarkitdownParser, "csv": MarkitdownParser},
|
||||
)
|
||||
|
||||
self.assertIs(isolated.get_parser_class("", "pptx"), MarkitdownParser)
|
||||
self.assertIs(isolated.get_parser_class(BUILTIN_ENGINE, "pptx"), MarkitdownParser)
|
||||
self.assertIs(isolated.get_parser_class("", "csv"), MarkitdownParser)
|
||||
self.assertIs(isolated.get_parser_class(BUILTIN_ENGINE, "csv"), MarkitdownParser)
|
||||
self.assertIs(isolated.get_parser_class(BUILTIN_ENGINE, "pdf"), PDFParser)
|
||||
self.assertIs(isolated.get_parser_class("", "pdf"), PDFParser)
|
||||
|
||||
with self.assertRaises(ValueError) as ctx:
|
||||
isolated.get_parser_class("", "xyz")
|
||||
self.assertIn("Unsupported file type: xyz", str(ctx.exception))
|
||||
|
||||
def test_actionable_error_lists_supporting_engines(self):
|
||||
isolated = ParserEngineRegistry()
|
||||
isolated.register(BUILTIN_ENGINE, {"pdf": PDFParser})
|
||||
isolated.register("opendataloader", {"xmind": XMindParser})
|
||||
|
||||
with self.assertRaises(ValueError) as ctx:
|
||||
isolated.get_parser_class(BUILTIN_ENGINE, "xmind")
|
||||
message = str(ctx.exception)
|
||||
self.assertIn("Configure one of:", message)
|
||||
self.assertIn("opendataloader", message)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ func TestNewReaderRoutesByEngine(t *testing.T) {
|
|||
{name: "builtin engine goes remote", engine: BuiltinEngineName, fileType: "md", want: remote},
|
||||
{name: "unset engine handles simple formats in Go", fileType: "csv", want: &SimpleFormatReader{}},
|
||||
{name: "unset engine sends complex formats to docreader", fileType: "docx", want: remote},
|
||||
{name: "default pptx engine is remote markitdown", engine: "markitdown", fileType: "pptx", want: remote},
|
||||
{name: "URLs always go to docreader", fileType: "md", isURL: true, want: remote},
|
||||
{name: "docreader-only engines fall through", engine: "markitdown", fileType: "docx", want: remote},
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ func TestListAllEnginesBuiltinIncludesDocumentFormats(t *testing.T) {
|
|||
for _, fileType := range engine.FileTypes {
|
||||
fileTypes[fileType] = true
|
||||
}
|
||||
for _, want := range []string{"html", "htm", "xmind"} {
|
||||
for _, want := range []string{"html", "htm", "xmind", "ppt", "pptx"} {
|
||||
if !fileTypes[want] {
|
||||
t.Errorf("builtin engine file types do not include %q: %v", want, engine.FileTypes)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -51,7 +51,8 @@ func (e *builtinEngine) Description() string { return "DocReader built-in parser
|
|||
|
||||
func (e *builtinEngine) FileTypes(_ bool) []string {
|
||||
return []string{
|
||||
"docx", "doc", "pdf", "md", "markdown", "xlsx", "xls", "epub",
|
||||
"docx", "doc", "pdf", "md", "markdown", "xlsx", "xls",
|
||||
"pptx", "ppt", "epub",
|
||||
"html", "htm", "mhtml", "xmind",
|
||||
"jpg", "jpeg", "png", "gif", "bmp", "tiff", "webp",
|
||||
"mp3", "wav", "m4a", "flac", "ogg",
|
||||
|
|
|
|||
|
|
@ -421,21 +421,20 @@ func oneOf(value string, allowed ...string) bool {
|
|||
}
|
||||
|
||||
// ResolveChatParserEngine returns the agent-configured parser engine for a
|
||||
// chat attachment file type, or "" when no rule matches. Mirrors the tenant
|
||||
// resolver in ParserEngineConfig.ResolveChatParserEngine.
|
||||
// chat attachment file type, or the type-level default when no rule matches.
|
||||
// Mirrors ParserEngineConfig.ResolveChatParserEngine.
|
||||
func (c *CustomAgentConfig) ResolveChatParserEngine(fileType string) string {
|
||||
if c == nil {
|
||||
return ""
|
||||
}
|
||||
fileType = strings.TrimPrefix(strings.ToLower(strings.TrimSpace(fileType)), ".")
|
||||
for _, rule := range c.ChatParserEngineRules {
|
||||
for _, candidate := range rule.FileTypes {
|
||||
if strings.TrimPrefix(strings.ToLower(strings.TrimSpace(candidate)), ".") == fileType {
|
||||
return strings.TrimSpace(rule.Engine)
|
||||
if c != nil {
|
||||
normalized := normalizeParserFileType(fileType)
|
||||
for _, rule := range c.ChatParserEngineRules {
|
||||
for _, candidate := range rule.FileTypes {
|
||||
if normalizeParserFileType(candidate) == normalized {
|
||||
return strings.TrimSpace(rule.Engine)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
return DefaultParserEngine(fileType)
|
||||
}
|
||||
|
||||
// Value implements driver.Valuer interface for CustomAgentConfig
|
||||
|
|
|
|||
|
|
@ -8,7 +8,8 @@ func TestCustomAgentConfigResolveChatParserEngine(t *testing.T) {
|
|||
{FileTypes: []string{"png", "jpg"}, Engine: "paddleocr_vl"},
|
||||
}}
|
||||
for input, expected := range map[string]string{
|
||||
"PDF": "mineru", ".pptx": "mineru", "png": "paddleocr_vl", "txt": "",
|
||||
"PDF": "mineru", ".pptx": "mineru", "png": "paddleocr_vl",
|
||||
"txt": "", "ppt": "markitdown",
|
||||
} {
|
||||
if actual := config.ResolveChatParserEngine(input); actual != expected {
|
||||
t.Fatalf("ResolveChatParserEngine(%q) = %q, want %q", input, actual, expected)
|
||||
|
|
@ -18,6 +19,9 @@ func TestCustomAgentConfigResolveChatParserEngine(t *testing.T) {
|
|||
if actual := nilConfig.ResolveChatParserEngine("pdf"); actual != "" {
|
||||
t.Fatalf("nil config resolved %q", actual)
|
||||
}
|
||||
if actual := nilConfig.ResolveChatParserEngine("pptx"); actual != "markitdown" {
|
||||
t.Fatalf("nil config pptx resolved %q, want markitdown", actual)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureDefaults_ThinkingExplicitFalse(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -249,7 +249,8 @@ type ChunkingConfig struct {
|
|||
// Separators
|
||||
Separators []string `yaml:"separators" json:"separators"`
|
||||
// ParserEngineRules configures which parser engine to use for each file type.
|
||||
// When empty, the builtin engine is used for all types.
|
||||
// When empty, DefaultParserEngine is used (builtin/simple routing, except
|
||||
// types that only a specific engine can parse, e.g. ppt/pptx → markitdown).
|
||||
ParserEngineRules []ParserEngineRule `yaml:"parser_engine_rules,omitempty" json:"parser_engine_rules,omitempty"`
|
||||
// EnableParentChild enables two-level parent-child chunking strategy.
|
||||
// When enabled, large parent chunks provide context while small child chunks
|
||||
|
|
@ -278,14 +279,28 @@ type ChunkingConfig struct {
|
|||
TableMetadataInstructions string `yaml:"table_metadata_instructions,omitempty" json:"table_metadata_instructions,omitempty"`
|
||||
}
|
||||
|
||||
// defaultParserEngineByType maps file types the builtin/simple engines cannot
|
||||
// parse to the only engine that can. Types omitted here keep empty-string
|
||||
// routing (Go simple formats, otherwise docreader builtin).
|
||||
var defaultParserEngineByType = map[string]string{
|
||||
"ppt": "markitdown",
|
||||
"pptx": "markitdown",
|
||||
}
|
||||
|
||||
// DefaultParserEngine returns the engine used when no parser_engine_rules
|
||||
// match. Empty string means builtin (docreader) or Go simple-format routing.
|
||||
func DefaultParserEngine(fileType string) string {
|
||||
return defaultParserEngineByType[normalizeParserFileType(fileType)]
|
||||
}
|
||||
|
||||
// ResolveParserEngine returns the engine name for the given file type
|
||||
// based on the configured rules. Returns empty string (builtin) when
|
||||
// no rule matches.
|
||||
// based on the configured rules. When no rule matches it returns the
|
||||
// type-level default (see DefaultParserEngine).
|
||||
func (c ChunkingConfig) ResolveParserEngine(fileType string) string {
|
||||
if rule := c.ResolveParserEngineRule(fileType); rule != nil {
|
||||
return rule.Engine
|
||||
}
|
||||
return ""
|
||||
return DefaultParserEngine(fileType)
|
||||
}
|
||||
|
||||
// ResolveParserEngineRule returns the parser rule for a file type.
|
||||
|
|
|
|||
|
|
@ -315,3 +315,31 @@ func TestEffectiveStorageProvider_CrossBackendDetection(t *testing.T) {
|
|||
dstSame.EffectiveStorageProvider(tenantDefault), sp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultParserEngine(t *testing.T) {
|
||||
for input, want := range map[string]string{
|
||||
"pptx": "markitdown", ".PPT": "markitdown", "ppt": "markitdown",
|
||||
"pdf": "", "csv": "", "docx": "", "": "",
|
||||
} {
|
||||
if got := DefaultParserEngine(input); got != want {
|
||||
t.Errorf("DefaultParserEngine(%q) = %q, want %q", input, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChunkingConfigResolveParserEngineDefaults(t *testing.T) {
|
||||
var empty ChunkingConfig
|
||||
if got := empty.ResolveParserEngine("pptx"); got != "markitdown" {
|
||||
t.Fatalf("empty rules ResolveParserEngine(pptx) = %q, want markitdown", got)
|
||||
}
|
||||
if got := empty.ResolveParserEngine("pdf"); got != "" {
|
||||
t.Fatalf("empty rules ResolveParserEngine(pdf) = %q, want empty", got)
|
||||
}
|
||||
|
||||
configured := ChunkingConfig{ParserEngineRules: []ParserEngineRule{
|
||||
{FileTypes: []string{"pptx"}, Engine: "mineru"},
|
||||
}}
|
||||
if got := configured.ResolveParserEngine(".PPTX"); got != "mineru" {
|
||||
t.Fatalf("configured ResolveParserEngine(pptx) = %q, want mineru", got)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,8 @@ func TestParserEngineConfigResolveChatParserEngine(t *testing.T) {
|
|||
{FileTypes: []string{"xlsx"}, Engine: "markitdown"},
|
||||
}}
|
||||
for input, expected := range map[string]string{
|
||||
"PDF": "mineru", ".docx": "mineru", "xlsx": "markitdown", "txt": "",
|
||||
"PDF": "mineru", ".docx": "mineru", "xlsx": "markitdown",
|
||||
"txt": "", "pptx": "markitdown", ".PPT": "markitdown",
|
||||
} {
|
||||
if actual := config.ResolveChatParserEngine(input); actual != expected {
|
||||
t.Fatalf("ResolveChatParserEngine(%q) = %q, want %q", input, actual, expected)
|
||||
|
|
@ -18,4 +19,7 @@ func TestParserEngineConfigResolveChatParserEngine(t *testing.T) {
|
|||
if actual := nilConfig.ResolveChatParserEngine("pdf"); actual != "" {
|
||||
t.Fatalf("nil config resolved %q", actual)
|
||||
}
|
||||
if actual := nilConfig.ResolveChatParserEngine("pptx"); actual != "markitdown" {
|
||||
t.Fatalf("nil config pptx resolved %q, want markitdown", actual)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -374,18 +374,17 @@ func ResolveMinerUParseMethod(method string, legacyOCREnabled *bool) string {
|
|||
}
|
||||
|
||||
func (c *ParserEngineConfig) ResolveChatParserEngine(fileType string) string {
|
||||
if c == nil {
|
||||
return ""
|
||||
}
|
||||
fileType = strings.TrimPrefix(strings.ToLower(strings.TrimSpace(fileType)), ".")
|
||||
for _, rule := range c.ChatParserEngineRules {
|
||||
for _, candidate := range rule.FileTypes {
|
||||
if strings.TrimPrefix(strings.ToLower(strings.TrimSpace(candidate)), ".") == fileType {
|
||||
return strings.TrimSpace(rule.Engine)
|
||||
if c != nil {
|
||||
normalized := normalizeParserFileType(fileType)
|
||||
for _, rule := range c.ChatParserEngineRules {
|
||||
for _, candidate := range rule.FileTypes {
|
||||
if normalizeParserFileType(candidate) == normalized {
|
||||
return strings.TrimSpace(rule.Engine)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
return DefaultParserEngine(fileType)
|
||||
}
|
||||
|
||||
// ToOverridesMap returns a map suitable for ParserEngineOverrides in parse requests.
|
||||
|
|
|
|||
Loading…
Reference in New Issue