Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

feat(parser): extract SVG text in Go picture ingestion (#20523)

Denis Ermakov543e16738b48
diff --git a/internal/ingestion/component/media_dispatch.go b/internal/ingestion/component/media_dispatch.go
index 419f3a9180..7977560a41 100644
--- a/internal/ingestion/component/media_dispatch.go
+++ b/internal/ingestion/component/media_dispatch.go
@@ -76,7 +76,8 @@ func maybeDispatchVideo(
fmt.Errorf("Parser: video parsing is not yet supported; underlying video analysis capability is pending")
}
-// Image dispatch: OCR followed by optional IMAGE2TEXT enhancement.
+// Image dispatch: OCR, or the document text of an SVG, followed by optional
+// IMAGE2TEXT enhancement.
func maybeDispatchImage(
ctx context.Context,
@@ -108,13 +109,27 @@ func maybeDispatchImage(
return parser.ParseResult{}, true, err
}
defer release()
- img, err := decodeDispatchImage(binary, useOCR)
- if err != nil {
- return parser.ParseResult{}, true, err
+ if len(binary) == 0 || len(binary) > parser.MaxImagePayloadBytes {
+ return parser.ParseResult{}, true, fmt.Errorf("parser: image payload exceeds size limits")
}
+ // SVG carries its text in the document, so it is read rather than
+ // rasterized for OCR, whatever the OCR switch says.
+ isSVG := isSVGFilename(filename)
var text string
- if useOCR {
- text, err = extractImageText(ctx, img)
+ var ocrErr error
+ if isSVG {
+ text, err = extractSVGText(ctx, binary)
+ if err != nil {
+ return parser.ParseResult{}, true, err
+ }
+ } else {
+ img, err := decodeDispatchImage(binary, useOCR)
+ if err != nil {
+ return parser.ParseResult{}, true, err
+ }
+ if useOCR {
+ text, ocrErr = extractImageText(ctx, img)
+ }
}
release()
parsed := dispatchParse(ctx, fileType, filename, binary, setups, progress.Window{})
@@ -129,8 +144,10 @@ func maybeDispatchImage(
m := parsed.JSON[0].ToMap()
m["text"] = text
parsed.JSON[0] = parser.DocItemFromMap(m)
- if err != nil {
- parsed.Warnings = append(parsed.Warnings, fmt.Sprintf("image OCR unavailable: %v", err))
+ if ocrErr != nil {
+ parsed.Warnings = append(parsed.Warnings, fmt.Sprintf("image OCR unavailable: %v", ocrErr))
+ } else if isSVG && text == "" {
+ parsed.Warnings = append(parsed.Warnings, "image SVG contains no text")
} else if useOCR && strings.TrimSpace(text) == "" {
parsed.Warnings = append(parsed.Warnings, "image OCR returned no text")
}
@@ -146,7 +163,10 @@ func maybeDispatchImage(
if err := ctx.Err(); err != nil {
return parsed, true, err
}
- if enableVisionEnhancement {
+ if enableVisionEnhancement && isSVG {
+ // Vision providers take raster images; raw SVG is not sent to them.
+ parsed.Warnings = append(parsed.Warnings, "image VLM enhancement skipped: SVG is not rasterized for vision models")
+ } else if enableVisionEnhancement {
// A setup with an explicit ocr_enabled switch always uses the global
// vision settings. Only legacy setups (no switch) carry the VLM model
// reference in parse_method, which also disabled OCR by construction.
@@ -173,9 +193,6 @@ func maybeDispatchImage(
}
func decodeDispatchImage(data []byte, decodeRaster bool) (image.Image, error) {
- if len(data) == 0 || len(data) > parser.MaxImagePayloadBytes {
- return nil, fmt.Errorf("parser: image payload exceeds size limits")
- }
config, _, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil {
return nil, fmt.Errorf("parser: decode image: %w", err)
diff --git a/internal/ingestion/component/svg_text.go b/internal/ingestion/component/svg_text.go
new file mode 100644
index 0000000000..7e6df69691
--- /dev/null
+++ b/internal/ingestion/component/svg_text.go
@@ -0,0 +1,256 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+// SVG is a vector format: the registered raster decoders cannot read it, and
+// its text is already present in the document. Image dispatch therefore reads
+// SVG text from the XML instead of rasterizing it for OCR.
+
+package component
+
+import (
+ "bytes"
+ "context"
+ "encoding/xml"
+ "errors"
+ "fmt"
+ "io"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "unicode"
+ "unicode/utf8"
+
+ htmlcharset "golang.org/x/net/html/charset"
+
+ "ragflow/internal/parser/parser"
+)
+
+// maxSVGDepth bounds element nesting: the XML decoder keeps one stack entry
+// per open element, so depth is the allocation an SVG payload could inflate.
+const maxSVGDepth = 1024
+
+// maxSVGEntities bounds the entity declarations read from a DOCTYPE.
+const maxSVGEntities = 64
+
+// svgEntityPattern matches the internal entity declarations of a DOCTYPE,
+// which some editors use for namespace URIs.
+var svgEntityPattern = regexp.MustCompile(`<!ENTITY\s+([A-Za-z_][\w.-]*)\s+(?:"([^"]*)"|'([^']*)')\s*>`)
+
+func isSVGFilename(filename string) bool {
+ return strings.EqualFold(filepath.Ext(filename), ".svg")
+}
+
+// extractSVGText returns the rendered text of an SVG document: the character
+// data of <text> elements and of the HTML embedded in <foreignObject>, one
+// line per text element, repositioned <tspan>, or HTML block.
+func extractSVGText(ctx context.Context, data []byte) (string, error) {
+ decoder := xml.NewDecoder(bytes.NewReader(bytes.TrimPrefix(data, []byte("\xef\xbb\xbf"))))
+ // transcoded records that the decoder no longer reads data byte for byte,
+ // so entity references cannot be counted in it.
+ var transcoded bool
+ decoder.CharsetReader = func(label string, input io.Reader) (io.Reader, error) {
+ transcoded = true
+ return htmlcharset.NewReaderLabel(label, input)
+ }
+ var expansion int64
+ entities := make(map[string]string, len(xml.HTMLEntity))
+ for name, value := range xml.HTMLEntity {
+ entities[name] = value
+ }
+ decoder.Entity = entities
+
+ var lines []string
+ var line strings.Builder
+ var pendingSpace bool
+ flush := func() {
+ if line.Len() > 0 {
+ lines = append(lines, line.String())
+ }
+ line.Reset()
+ pendingSpace = false
+ }
+ // depth counts open elements; textDepth and skipDepth record the depth at
+ // which a text container or a non-rendered subtree was opened.
+ var depth, textDepth, skipDepth int
+ // switches holds the open <switch> elements, innermost last. A switch
+ // renders one child, so the children after its first are skipped.
+ var switches []svgSwitch
+ var sawRoot bool
+ for {
+ if err := ctx.Err(); err != nil {
+ return "", err
+ }
+ token, err := decoder.Token()
+ if errors.Is(err, io.EOF) {
+ break
+ }
+ if err != nil {
+ return "", fmt.Errorf("parser: decode SVG: %w", err)
+ }
+ switch el := token.(type) {
+ case xml.Directive:
+ if transcoded {
+ continue
+ }
+ matches := svgEntityPattern.FindAllSubmatch(el, maxSVGEntities+1)
+ if len(matches) > maxSVGEntities {
+ return "", fmt.Errorf("parser: decode SVG: DOCTYPE declares more than %d entities", maxSVGEntities)
+ }
+ // Entity values are substituted as literal text and never parsed
+ // again, so a declaration cannot expand recursively. Repeated
+ // references still multiply a value, so the total they expand to
+ // is budgeted before the decoder substitutes any of them.
+ for _, match := range matches {
+ value := string(match[2]) + string(match[3])
+ references := bytes.Count(data, []byte("&"+string(match[1])+";"))
+ expansion += int64(references) * int64(len(value))
+ if expansion > parser.MaxImagePayloadBytes {
+ return "", errors.New("parser: decode SVG: entity expansion exceeds size limits")
+ }
+ entities[string(match[1])] = value
+ }
+ case xml.StartElement:
+ depth++
+ if depth > maxSVGDepth {
+ return "", fmt.Errorf("parser: decode SVG: elements nest deeper than %d levels", maxSVGDepth)
+ }
+ name := el.Name.Local
+ if depth == 1 {
+ if name != "svg" {
+ return "", fmt.Errorf("parser: decode SVG: root element is %q, not svg", name)
+ }
+ sawRoot = true
+ }
+ inner := len(switches) - 1
+ switch {
+ case skipDepth > 0:
+ case svgNonRendered[name] || isSVGHidden(el.Attr) || inner >= 0 && switches[inner].rendered && depth == switches[inner].depth+1:
+ skipDepth = depth
+ case name == "switch":
+ switches = append(switches, svgSwitch{depth: depth})
+ case textDepth == 0:
+ if name == "text" || name == "foreignObject" {
+ textDepth = depth
+ }
+ case startsSVGTextLine(name, el.Attr):
+ flush()
+ }
+ case xml.EndElement:
+ if textDepth > 0 && skipDepth == 0 && (depth == textDepth || svgTextBlocks[el.Name.Local]) {
+ flush()
+ }
+ if depth == textDepth {
+ textDepth = 0
+ }
+ if depth == skipDepth {
+ skipDepth = 0
+ }
+ if inner := len(switches) - 1; inner >= 0 {
+ switch depth {
+ case switches[inner].depth + 1:
+ switches[inner].rendered = true
+ case switches[inner].depth:
+ switches = switches[:inner]
+ }
+ }
+ depth--
+ case xml.CharData:
+ if textDepth == 0 || skipDepth > 0 {
+ continue
+ }
+ // Collapse whitespace runs while copying, as SVG rendering does.
+ for len(el) > 0 {
+ r, size := utf8.DecodeRune(el)
+ el = el[size:]
+ if unicode.IsSpace(r) {
+ pendingSpace = true
+ continue
+ }
+ if pendingSpace && line.Len() > 0 {
+ line.WriteByte(' ')
+ }
+ pendingSpace = false
+ line.WriteRune(r)
+ }
+ }
+ }
+ if !sawRoot {
+ return "", errors.New("parser: decode SVG: no root element")
+ }
+ return strings.Join(lines, "\n"), nil
+}
+
+// svgSwitch is an open <switch> element: the depth it was opened at, and
+// whether its first child has already been read.
+type svgSwitch struct {
+ depth int
+ rendered bool
+}
+
+// svgNonRendered lists the elements whose character data is not drawn where
+// it appears.
+var svgNonRendered = map[string]bool{
+ "style": true, "script": true, "title": true, "desc": true, "metadata": true,
+ "defs": true, "symbol": true, "clipPath": true, "mask": true,
+}
+
+// svgHiddenStyle matches a style attribute that removes its element from
+// rendering.
+var svgHiddenStyle = regexp.MustCompile(`(?i)(?:^|;)\s*display\s*:\s*none\s*(?:;|$)`)
+
+// isSVGHidden reports whether an element's attributes set display to none.
+func isSVGHidden(attrs []xml.Attr) bool {
+ for _, attr := range attrs {
+ switch attr.Name.Local {
+ case "display":
+ if strings.TrimSpace(attr.Value) == "none" {
+ return true
+ }
+ case "style":
+ if svgHiddenStyle.MatchString(attr.Value) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+// svgTextBlocks lists the HTML elements inside <foreignObject> that break the
+// line they appear in.
+var svgTextBlocks = map[string]bool{
+ "br": true, "div": true, "p": true, "li": true, "tr": true, "td": true, "th": true,
+ "dt": true, "dd": true,
+ "h1": true, "h2": true, "h3": true, "h4": true, "h5": true, "h6": true,
+}
+
+// startsSVGTextLine reports whether an element nested in a text container
+// begins a new line: an HTML block, or a <tspan> that moves the baseline.
+// A <tspan> that only sets x stays inline, since exporters position single
+// glyphs or words that way.
+func startsSVGTextLine(name string, attrs []xml.Attr) bool {
+ if svgTextBlocks[name] {
+ return true
+ }
+ if name != "tspan" {
+ return false
+ }
+ for _, attr := range attrs {
+ if attr.Name.Local == "y" || attr.Name.Local == "dy" {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/ingestion/component/svg_text_test.go b/internal/ingestion/component/svg_text_test.go
new file mode 100644
index 0000000000..06f36e8fba
--- /dev/null
+++ b/internal/ingestion/component/svg_text_test.go
@@ -0,0 +1,223 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package component
+
+import (
+ "context"
+ _ "embed"
+ "encoding/json"
+ "os"
+ "strings"
+ "testing"
+
+ "gorm.io/gorm"
+
+ deepdoctype "ragflow/internal/deepdoc/parser/type"
+ "ragflow/internal/entity"
+ modelModule "ragflow/internal/entity/models"
+ "ragflow/internal/parser/parser"
+ "ragflow/internal/utility"
+)
+
+//go:embed testdata/picture_text.svg
+var pictureSVGFixture []byte
+
+const pictureSVGFixtureText = "HELLO WORLD\nQuarterly revenue\nR&D budget\nNode label\nSecond line"
+
+func TestExtractSVGText(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ svg string
+ want string
+ }{
+ {"fixture", string(pictureSVGFixture), pictureSVGFixtureText},
+ {"inline tspans stay on one line", `<svg xmlns="http://www.w3.org/2000/svg"><text>Hel<tspan fill="red">lo</tspan> there</text></svg>`, "Hello there"},
+ {"tspans that only set x stay on one line", `<svg><text y="10"><tspan x="0">H</tspan><tspan x="8">i</tspan></text></svg>`, "Hi"},
+ {"whitespace is collapsed", "<svg><text>\n a \t b\n</text></svg>", "a b"},
+ {"tooltip inside text is ignored", `<svg><text><title>tooltip</title>kept</text></svg>`, "kept"},
+ {"prefixed namespace", `<s:svg xmlns:s="http://www.w3.org/2000/svg"><s:text>kept</s:text></s:svg>`, "kept"},
+ {"doctype entities", `<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" [<!ENTITY ns_svg "http://www.w3.org/2000/svg"><!ENTITY label 'kept'>]><svg xmlns="&ns_svg;"><text>&label;</text></svg>`, "kept"},
+ {"utf-8 byte order mark", "\xef\xbb\xbf<?xml version=\"1.0\" encoding=\"UTF-8\"?><svg><text>kept</text></svg>", "kept"},
+ {"cdata", `<svg><text><![CDATA[1 < 2]]></text></svg>`, "1 < 2"},
+ {"text outside text elements is ignored", `<svg><title>t</title><desc>d</desc><g>stray</g><text>kept</text></svg>`, "kept"},
+ {"style and script are ignored", `<svg><foreignObject><div xmlns="http://www.w3.org/1999/xhtml"><style>p{}</style><script>x()</script>kept</div></foreignObject></svg>`, "kept"},
+ {"table cells stay apart", `<svg><foreignObject><table xmlns="http://www.w3.org/1999/xhtml"><tr><th>h</th><td>a</td><td>b</td></tr></table><dl xmlns="http://www.w3.org/1999/xhtml"><dt>t</dt><dd>d</dd></dl></foreignObject></svg>`, "h\na\nb\nt\nd"},
+ {"definitions are not rendered", `<svg><defs><text>def</text></defs><symbol><text>sym</text></symbol><clipPath><text>clip</text></clipPath><mask><text>mask</text></mask><text>kept</text></svg>`, "kept"},
+ {"hidden elements are ignored", `<svg><text display="none">a</text><g style="fill:red; display : none"><text>b</text></g><text>kept<tspan style="display:none">c</tspan></text></svg>`, "kept"},
+ {"switch renders its first child only", `<svg><switch><foreignObject><div xmlns="http://www.w3.org/1999/xhtml">label</div></foreignObject><text>fallback</text></switch><switch><g/><a><text>Text is not SVG</text></a></switch><text>kept</text></svg>`, "label\nkept"},
+ {"nested switch", `<svg><switch><g><switch><text>a</text><text>b</text></switch><text>c</text></g><text>d</text></switch></svg>`, "a\nc"},
+ {"line break element", `<svg><foreignObject><div xmlns="http://www.w3.org/1999/xhtml">a<br/>b</div></foreignObject></svg>`, "a\nb"},
+ {"non-utf8 encoding", "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><svg><text>caf\xe9</text></svg>", "café"},
+ {"no text", `<svg xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1"/></svg>`, ""},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ got, err := extractSVGText(t.Context(), []byte(tc.svg))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got != tc.want {
+ t.Fatalf("text = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestExtractSVGTextRejectsInvalidInput(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ svg string
+ want string
+ }{
+ {"not xml", "\x89PNG\r\n\x1a\n", "decode SVG"},
+ {"empty document", "<?xml version=\"1.0\"?>", "no root element"},
+ {"unclosed element", `<svg><text>a</text>`, "decode SVG"},
+ {"mismatched tags", `<svg><text>a</g></svg>`, "decode SVG"},
+ {"undefined entity", `<svg><text>&undefined;</text></svg>`, "decode SVG"},
+ {"other root", `<html><body>a</body></html>`, `root element is "html"`},
+ {"excessive nesting", "<svg>" + strings.Repeat("<g>", maxSVGDepth), "nest deeper"},
+ {"entity expansion", `<!DOCTYPE svg [<!ENTITY a "` + strings.Repeat("x", 1<<20) + `">]><svg><text>` + strings.Repeat("&a;", 64) + `</text></svg>`, "entity expansion"},
+ {"too many entities", `<!DOCTYPE svg [` + strings.Repeat(`<!ENTITY a "x">`, maxSVGEntities+1) + `]><svg/>`, "more than"},
+ {"entities in a transcoded document", "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><!DOCTYPE svg [<!ENTITY a \"x\">]><svg><text>&a;</text></svg>", "invalid character entity"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ got, err := extractSVGText(t.Context(), []byte(tc.svg))
+ if err == nil || !strings.Contains(err.Error(), tc.want) {
+ t.Fatalf("text = %q, error = %v, want error containing %q", got, err, tc.want)
+ }
+ })
+ }
+}
+
+func TestExtractSVGTextHonorsCancellation(t *testing.T) {
+ ctx, cancel := context.WithCancel(t.Context())
+ cancel()
+ if _, err := extractSVGText(ctx, pictureSVGFixture); err == nil {
+ t.Fatal("expected a cancellation error")
+ }
+}
+
+// TestMaybeDispatchImageSVG runs the picture template on an SVG. The text
+// comes from the document itself, so it needs neither the local OCR analyzer
+// nor a vision model, and the raw SVG is never sent to a vision provider.
+func TestMaybeDispatchImageSVG(t *testing.T) {
+ templateData, err := os.ReadFile("../pipeline/template/ingestion_pipeline_picture.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var template struct {
+ DSL struct {
+ Components map[string]struct {
+ Obj struct{ Params map[string]any }
+ }
+ }
+ }
+ if err := json.Unmarshal(templateData, &template); err != nil {
+ t.Fatal(err)
+ }
+ params := template.DSL.Components["Parser:ViewsCaptureLight"].Obj.Params
+ original := deepdoctype.NativeDocAnalyzerFactory
+ deepdoctype.NativeDocAnalyzerFactory = func() (deepdoctype.DocAnalyzer, bool) {
+ t.Error("SVG must not reach the raster OCR analyzer")
+ return nil, false
+ }
+ t.Cleanup(func() { deepdoctype.NativeDocAnalyzerFactory = original })
+ for _, tc := range []struct {
+ name string
+ ocr bool
+ enabled bool
+ }{
+ {"vision disabled", true, false},
+ {"vision enabled", true, true},
+ {"ocr off", false, true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ driver := &imagePromptCaptureDriver{}
+ originalTenant, originalConfig := resolveTenantModelByType, resolveModelConfig
+ resolveTenantModelByType = func(context.Context, *gorm.DB, string, entity.ModelType) (modelModule.ModelDriver, string, *modelModule.APIConfig, int, error) {
+ return driver, "vision", &modelModule.APIConfig{}, 0, nil
+ }
+ resolveModelConfig = func(context.Context, *gorm.DB, string, entity.ModelType, string) (modelModule.ModelDriver, string, *modelModule.APIConfig, int, error) {
+ return driver, "vision", &modelModule.APIConfig{}, 0, nil
+ }
+ t.Cleanup(func() { resolveTenantModelByType, resolveModelConfig = originalTenant, originalConfig })
+ params["image"].(map[string]any)["ocr_enabled"] = tc.ocr
+ params["enable_vision_enhancement"] = tc.enabled
+ component, err := NewParserComponent(params)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pc := component.(*ParserComponent)
+ result, err := pc.Invoke(t.Context(), nil, map[string]any{"name": "diagram.svg", "file_type": "image", "binary": pictureSVGFixture, "tenant_id": "t1"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ jsonDocs, _ := result["json"].([]parser.DocItem)
+ items := parser.ItemsToMaps(jsonDocs)
+ if len(items) != 1 || items[0]["text"] != pictureSVGFixtureText {
+ t.Fatalf("items = %+v, want text %q", items, pictureSVGFixtureText)
+ }
+ payload, _ := items[0]["image"].(string)
+ if !strings.HasPrefix(payload, "data:image/svg+xml;base64,") || items[0]["doc_type_kwd"] != "image" {
+ t.Fatalf("missing SVG image attachment: %+v", items)
+ }
+ if len(driver.captured) != 0 {
+ t.Fatalf("raw SVG was sent to the vision model: %#v", driver.captured)
+ }
+ })
+ }
+}
+
+func TestMaybeDispatchImageSVGWarnings(t *testing.T) {
+ driver := &imagePromptCaptureDriver{}
+ original := resolveTenantModelByType
+ resolveTenantModelByType = func(context.Context, *gorm.DB, string, entity.ModelType) (modelModule.ModelDriver, string, *modelModule.APIConfig, int, error) {
+ return driver, "vision", &modelModule.APIConfig{}, 0, nil
+ }
+ t.Cleanup(func() { resolveTenantModelByType = original })
+ textless := []byte(`<svg xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1"/></svg>`)
+ result, handled, err := maybeDispatchImage(t.Context(), nil, utility.FileTypeVISUAL, "shape.SVG", textless, map[string]any{"tenant_id": "t1"}, defaultSetups(), true, visionSettings{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !handled || len(result.JSON) != 1 || result.JSON[0].ToMap()["text"] != "" || result.JSON[0].ToMap()["image"] == "" {
+ t.Fatalf("result = %+v, handled = %v", result, handled)
+ }
+ if len(driver.captured) != 0 {
+ t.Fatalf("raw SVG was sent to the vision model: %#v", driver.captured)
+ }
+ warnings := strings.Join(result.Warnings, "\n")
+ for _, want := range []string{"image SVG contains no text", "image VLM enhancement skipped: SVG is not rasterized"} {
+ if !strings.Contains(warnings, want) {
+ t.Fatalf("warnings = %q, want %q", warnings, want)
+ }
+ }
+}
+
+func TestMaybeDispatchImageRejectsInvalidSVG(t *testing.T) {
+ for _, ocr := range []bool{true, false} {
+ setups := defaultSetups()
+ setups["image"]["ocr_enabled"] = ocr
+ _, handled, err := maybeDispatchImage(t.Context(), nil, utility.FileTypeVISUAL, "broken.svg", []byte(`<svg><text>a</svg>`), nil, setups, false, visionSettings{})
+ if !handled || err == nil || !strings.Contains(err.Error(), "parser: decode SVG") {
+ t.Fatalf("ocr %v: handled = %v, error = %v, want SVG decode error", ocr, handled, err)
+ }
+ _, _, err = maybeDispatchImage(t.Context(), nil, utility.FileTypeVISUAL, "empty.svg", nil, nil, setups, false, visionSettings{})
+ if err == nil || !strings.Contains(err.Error(), "size limits") {
+ t.Fatalf("ocr %v: error = %v, want size limit error", ocr, err)
+ }
+ }
+}
diff --git a/internal/ingestion/component/testdata/picture_text.svg b/internal/ingestion/component/testdata/picture_text.svg
new file mode 100644
index 0000000000..77992e2cbf
--- /dev/null
+++ b/internal/ingestion/component/testdata/picture_text.svg
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg" width="320" height="160" viewBox="0 0 320 160">
+ <title>Fixture</title>
+ <style>text { font-family: sans-serif; font-size: 20px; }</style>
+ <rect width="320" height="160" fill="#ffffff"/>
+ <text x="20" y="40">HELLO WORLD</text>
+ <text x="20" y="80">
+ <tspan x="20" dy="0">Quarterly revenue</tspan>
+ <tspan x="20" dy="24">R&amp;D <tspan font-weight="bold">budget</tspan></tspan>
+ </text>
+ <foreignObject x="20" y="110" width="280" height="40">
+ <div xmlns="http://www.w3.org/1999/xhtml"><p>Node label</p><p>Second line</p></div>
+ </foreignObject>
+</svg>