fix(docparser): resolve remote images referenced by HTML img tags (#2355)
Remote http(s) images written as <img src="..."> reached no resolver.
Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML
relative paths each had their own pass, but nothing claimed the remaining
combination, so those images were dropped without a log line and the
multimodal stage was skipped for documents that rely on HTML for layout.
ResolveRemoteImages now scans HTML img tags with a quoted src as a second
pass and rewrites only the src attribute value, leaving the tag intact
because the surrounding markup is why these documents use HTML at all.
The per-image work (whitelist, SSRF, download, icon filter, upload) moves
into one helper so the two syntaxes cannot drift apart on policy. Each
pass carries its own image budget; sharing one would let HTML images eat
into the number of Markdown images a document already gets resolved.
An attribute value is trimmed, HTML-unescaped and its scheme lowercased
before use, because HTML permits padding, spells a query separator &
and tolerates any scheme case, while every fetcher downstream compares the
scheme byte-for-byte. Markdown targets get none of that normalization, so
no Markdown reference resolves differently than it does today. A
whitelisted host keeps serving the image from where it already lives, and
its span is rewritten with the normalized URL rather than the raw attribute
text: later stages both locate the image by searching the document for its
serving URL and fetch that same string, so the two have to agree.
The src attribute must now be preceded by whitespace, so a hyphenated
attribute name is no longer mistaken for it. Among HTML tags this cuts two
ways: one carrying both a hyphenated *-src and a real src now resolves the
real src instead of the placeholder, while one carrying only a hyphenated
*-src is no longer resolved at all. Recovering the latter needs an
attribute parser rather than a regex, and resolving a lazy-loading
placeholder while the real image goes unvisited is the worse of the two
failures. Both halves are pinned by tests.
Image-derived text also has to survive into the answer, which is why this
touches internal/searchutil. The chat enricher and the image_info filters
matched Markdown links only, so an HTML-only passage looked image-free:
every entry was dropped and the model received bare markup with the
caption and OCR text stripped, even though the analysis had run. Both now
recognise HTML img tags through one shared regex, so a tag the parser
stores can always be matched back. Both syntaxes are located against the
original passage and spliced in a single pass; scanning one regex over the
other's output let a metadata block that itself quotes an image reference
be rescanned and duplicated. The chat variant still enriches only images
present in the passage, so orphan entries stay out.
Known limits:
- An unquoted src and a srcset-only tag are not matched, nor is a tag
whose attribute values hold a bare > or a quoted src= of their own.
- imgHTMLDataURI still matches src without a boundary, so a data-src
holding a base64 placeholder is consumed as if it were the src and the
whole tag replaced. Worth the same fix, but it changes what an existing
lazy-loading document resolves, so it belongs on its own.
- A reference shown as a documentation example is rewritten like any
other. Recognising code spans needs a Markdown parser; a hand-rolled
scanner risks the far worse failure of treating a document's real
screenshots as examples.
- Rewriting a whitelisted src writes the unescaped URL back into an HTML
attribute, so a query parameter whose name spells an entity renders
differently than the author wrote it. Keeping the encoded form would
mean unescaping on every matcher instead.
- Image text reaches the model only when the whole reference falls inside
the retrieved window; an img tag is several times longer than a
Markdown link and straddles a chunk boundary more often.
- A reference repeated in one document is fetched once per occurrence,
which is what gives each chunk its own analysed copy.
- Nothing bounds how long one document's fetches may take in total.
- Parent-context pruning removes only Markdown images.
Co-authored-by: wizardchen <wizardchen@tencent.com>
main
parent
82d3e0b271
commit
c9a342d965
|
|
@ -4,7 +4,9 @@ import (
|
|||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html"
|
||||
"image"
|
||||
_ "image/gif"
|
||||
_ "image/jpeg"
|
||||
|
|
@ -21,6 +23,7 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/searchutil"
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
|
|
@ -333,9 +336,15 @@ var imgHTMLDataURI = regexp.MustCompile(
|
|||
`(?i)<img\s[^>]*?src\s*=\s*["'](data:image/[^;]+;base64,[^"']+)["'][^>]*?/?\s*>`,
|
||||
)
|
||||
|
||||
var imgHTMLRelativeSrc = regexp.MustCompile(
|
||||
`(?i)<img\b([^>]*?)\bsrc\s*=\s*['"]([^'"]+)['"]([^>]*)>`,
|
||||
)
|
||||
// imgHTMLSrc matches an HTML <img> tag carrying a quoted src attribute. It does
|
||||
// not care what the src points at — callers select the references they handle by
|
||||
// inspecting the scheme, which is how the relative and the remote paths divide
|
||||
// the same tags between them.
|
||||
//
|
||||
// Shared with the search layer so that an image stored here can always be
|
||||
// matched back to the tag it came from. See searchutil.HTMLImageSrcRegex for
|
||||
// the submatch layout and the known limits.
|
||||
var imgHTMLSrc = searchutil.HTMLImageSrcRegex
|
||||
|
||||
// ResolveHTMLDataURIImages finds <img src="data:image/*;base64,..."> tags in markdown,
|
||||
// decodes the images, stores them via fileSvc, and replaces each tag with a markdown
|
||||
|
|
@ -410,7 +419,7 @@ func (r *ImageResolver) ResolveRelativeHTMLImages(
|
|||
refMap map[string]types.ImageRef,
|
||||
savedRefs map[string]StoredImage,
|
||||
) (updatedMarkdown string, images []StoredImage, err error) {
|
||||
matches := imgHTMLRelativeSrc.FindAllStringSubmatchIndex(markdown, -1)
|
||||
matches := imgHTMLSrc.FindAllStringSubmatchIndex(markdown, -1)
|
||||
if len(matches) == 0 {
|
||||
return markdown, nil, nil
|
||||
}
|
||||
|
|
@ -738,15 +747,218 @@ func (r *ImageResolver) ResolveDataURIImages(
|
|||
return markdown, images, nil
|
||||
}
|
||||
|
||||
// ResolveRemoteImages scans a Markdown string for image references whose URL
|
||||
// is http:// or https://, downloads each one through an SSRF-safe HTTP client,
|
||||
// uploads the bytes via fileSvc, and replaces the original URL with the
|
||||
// provider:// serving URL.
|
||||
// errRemoteImageIsIcon marks the one skip reason worth aggregating: a page can
|
||||
// carry hundreds of tracking pixels and spacer GIFs, and a line for each would
|
||||
// drown the reasons an operator actually needs to see.
|
||||
var errRemoteImageIsIcon = errors.New("filtered out as icon")
|
||||
|
||||
// remoteImageResult describes one image that was fetched successfully.
|
||||
type remoteImageResult struct {
|
||||
// ServingURL is empty when KeepOriginalURL is set. The caller fills it in
|
||||
// with the normalized request URL — NOT the raw document bytes. Later stages
|
||||
// both search the document for this string and fetch it, so a padded or
|
||||
// entity-encoded value satisfies neither.
|
||||
ServingURL string
|
||||
MimeType string
|
||||
// KeepOriginalURL marks a whitelisted host. Its bytes are downloaded so that
|
||||
// OCR/caption analysis can run, but it is not uploaded: the image keeps being
|
||||
// served from its original host, reached through the normalized URL.
|
||||
KeepOriginalURL bool
|
||||
}
|
||||
|
||||
// fetchAndStoreRemoteImage applies the SSRF policy, downloads the image,
|
||||
// rejects icons and uploads the bytes to storage.
|
||||
//
|
||||
// Images that fail SSRF validation, exceed size limits, or cannot be downloaded
|
||||
// are left unchanged (the original URL is preserved).
|
||||
// Both the Markdown and the HTML scan go through here so that the SSRF check,
|
||||
// the icon filter and the whitelist behaviour cannot drift apart between the
|
||||
// two syntaxes.
|
||||
func fetchAndStoreRemoteImage(
|
||||
ctx context.Context,
|
||||
client *http.Client,
|
||||
fileSvc interfaces.FileService,
|
||||
tenantID uint64,
|
||||
imgURL string,
|
||||
) (*remoteImageResult, error) {
|
||||
whitelisted := isWhitelistedImageHost(imgURL)
|
||||
|
||||
if !whitelisted {
|
||||
if err := secutils.ValidateURLForSSRF(imgURL); err != nil {
|
||||
return nil, fmt.Errorf("blocked by SSRF policy: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
data, mimeType, err := downloadImage(ctx, client, imgURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("download: %w", err)
|
||||
}
|
||||
|
||||
if isIconImage(data) {
|
||||
return nil, errRemoteImageIsIcon
|
||||
}
|
||||
|
||||
if whitelisted {
|
||||
return &remoteImageResult{MimeType: mimeType, KeepOriginalURL: true}, nil
|
||||
}
|
||||
|
||||
ext := extFromMime(mimeType)
|
||||
if ext == "" {
|
||||
ext = extFromURLPath(imgURL)
|
||||
}
|
||||
if ext == "" {
|
||||
ext = ".png" // safe default
|
||||
}
|
||||
servingURL, err := fileSvc.SaveBytes(ctx, data, tenantID, uuid.New().String()+ext, false)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("save: %w", err)
|
||||
}
|
||||
return &remoteImageResult{ServingURL: servingURL, MimeType: mimeType}, nil
|
||||
}
|
||||
|
||||
// isRemoteHTTPURL reports whether raw is an absolute http(s) URL.
|
||||
//
|
||||
// Returns the updated Markdown and a list of successfully stored images.
|
||||
// The comparison is deliberately byte-exact. Downstream fetchers compare the
|
||||
// scheme the same way, so anything accepted here has to be spelled the way they
|
||||
// expect; per-syntax normalization belongs in the SrcOf of the scan that needs
|
||||
// it, not in this predicate.
|
||||
func isRemoteHTTPURL(raw string) bool {
|
||||
return strings.HasPrefix(raw, "http://") || strings.HasPrefix(raw, "https://")
|
||||
}
|
||||
|
||||
// remotePassSpec describes one scan of a document: which references it matches,
|
||||
// where the URL sits inside a match, and how to turn the raw document bytes into
|
||||
// the URL to request.
|
||||
type remotePassSpec struct {
|
||||
Pattern *regexp.Regexp
|
||||
URLGroup int
|
||||
Syntax string
|
||||
SrcOf func(string) string
|
||||
}
|
||||
|
||||
// remotePassStats accumulates the reasons a scan passed a reference over, so
|
||||
// that a partially resolved document can be explained afterwards.
|
||||
type remotePassStats struct {
|
||||
resolved int
|
||||
iconSkips int
|
||||
overBudget int
|
||||
}
|
||||
|
||||
func (s *remotePassStats) report(syntax string) {
|
||||
if s.iconSkips > 0 {
|
||||
log.Printf("INFO: skipped %d %s remote image(s) as icons", s.iconSkips, syntax)
|
||||
}
|
||||
if s.overBudget > 0 {
|
||||
log.Printf(
|
||||
"WARN: remote image limit of %d reached for %s images; %d reference(s) left unresolved",
|
||||
maxRemoteImages, syntax, s.overBudget,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// resolveRemoteImagePass rewrites every remote http(s) reference matched by
|
||||
// spec.Pattern, replacing the span of its URL capture group with the URL the
|
||||
// image will be served from: the storage URL, or the normalized original for a
|
||||
// whitelisted host. Matches are walked in reverse so the spans still to be
|
||||
// processed stay valid after each replacement.
|
||||
func resolveRemoteImagePass(
|
||||
ctx context.Context,
|
||||
markdown string,
|
||||
spec remotePassSpec,
|
||||
client func() *http.Client,
|
||||
fileSvc interfaces.FileService,
|
||||
tenantID uint64,
|
||||
) (string, []StoredImage) {
|
||||
matches := spec.Pattern.FindAllStringSubmatchIndex(markdown, -1)
|
||||
if len(matches) == 0 {
|
||||
return markdown, nil
|
||||
}
|
||||
|
||||
var (
|
||||
images []StoredImage
|
||||
stats remotePassStats
|
||||
)
|
||||
|
||||
for i := len(matches) - 1; i >= 0; i-- {
|
||||
m := matches[i]
|
||||
start, end := m[2*spec.URLGroup], m[2*spec.URLGroup+1]
|
||||
if start < 0 {
|
||||
continue
|
||||
}
|
||||
imgURL := spec.SrcOf(markdown[start:end])
|
||||
if !isRemoteHTTPURL(imgURL) {
|
||||
continue
|
||||
}
|
||||
|
||||
if ctx.Err() != nil {
|
||||
log.Printf("WARN: remote image resolution cancelled: %v", ctx.Err())
|
||||
break
|
||||
}
|
||||
|
||||
if stats.resolved >= maxRemoteImages {
|
||||
stats.overBudget++
|
||||
continue
|
||||
}
|
||||
|
||||
res, err := fetchAndStoreRemoteImage(ctx, client(), fileSvc, tenantID, imgURL)
|
||||
if err != nil {
|
||||
if errors.Is(err, errRemoteImageIsIcon) {
|
||||
stats.iconSkips++
|
||||
} else {
|
||||
log.Printf("WARN: skipped %s remote image %s: %v", spec.Syntax, imgURL, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
stats.resolved++
|
||||
|
||||
// A whitelisted host is served from where it already lives, so the
|
||||
// document keeps pointing there. The span is still rewritten with the
|
||||
// normalized URL: later stages both locate the image by searching the
|
||||
// document for its ServingURL and fetch that same string, so the two have
|
||||
// to agree, and an entity-encoded or padded attribute value satisfies
|
||||
// neither.
|
||||
servingURL := res.ServingURL
|
||||
if res.KeepOriginalURL {
|
||||
servingURL = imgURL
|
||||
}
|
||||
|
||||
images = append(images, StoredImage{
|
||||
OriginalRef: imgURL,
|
||||
ServingURL: servingURL,
|
||||
MimeType: res.MimeType,
|
||||
})
|
||||
markdown = markdown[:start] + servingURL + markdown[end:]
|
||||
}
|
||||
|
||||
stats.report(spec.Syntax)
|
||||
return markdown, images
|
||||
}
|
||||
|
||||
// htmlAttrSrc normalizes an HTML src attribute value into the URL to request.
|
||||
//
|
||||
// Three things are HTML-specific. An attribute value may be padded, so it is
|
||||
// trimmed — on both sides of the decode, because an entity can itself expand to
|
||||
// whitespace. It may carry entities, and `&` is the correct spelling of a
|
||||
// query separator, so it is unescaped. And the scheme may be written in any
|
||||
// case, while every fetcher downstream compares it byte-for-byte, so it is
|
||||
// lowercased.
|
||||
//
|
||||
// Markdown targets get none of this: they are handed through unchanged so that
|
||||
// existing documents resolve exactly the references they resolve today.
|
||||
func htmlAttrSrc(raw string) string {
|
||||
src := strings.TrimSpace(html.UnescapeString(strings.TrimSpace(raw)))
|
||||
if i := strings.Index(src, "://"); i > 0 {
|
||||
src = strings.ToLower(src[:i]) + src[i:]
|
||||
}
|
||||
return src
|
||||
}
|
||||
|
||||
// markdownSrc hands a Markdown image target through untouched. Markdown has no
|
||||
// attribute quoting or entity encoding to undo, and leaving it alone is what
|
||||
// keeps existing documents resolving exactly what they resolve today.
|
||||
func markdownSrc(raw string) string { return raw }
|
||||
|
||||
// ResolveRemoteImages downloads remote http(s) images into storage and points
|
||||
// the document at the stored copies. Both Markdown image syntax and HTML <img>
|
||||
// tags with a quoted src are covered.
|
||||
func (r *ImageResolver) ResolveRemoteImages(
|
||||
ctx context.Context,
|
||||
markdown string,
|
||||
|
|
@ -755,101 +967,38 @@ func (r *ImageResolver) ResolveRemoteImages(
|
|||
) (updatedMarkdown string, images []StoredImage, err error) {
|
||||
markdown = UnwrapLinkedImages(markdown)
|
||||
|
||||
matches := imgMarkdownPattern.FindAllStringSubmatchIndex(markdown, -1)
|
||||
if len(matches) == 0 {
|
||||
return markdown, nil, nil
|
||||
// The client owns a dedicated transport, so it is built only once a scan
|
||||
// actually has something to fetch.
|
||||
var httpClient *http.Client
|
||||
client := func() *http.Client {
|
||||
if httpClient == nil {
|
||||
httpClient = secutils.NewSSRFSafeHTTPClient(secutils.SSRFSafeHTTPClientConfig{
|
||||
Timeout: remoteImageFetchTimeout,
|
||||
MaxRedirects: 5,
|
||||
})
|
||||
}
|
||||
return httpClient
|
||||
}
|
||||
|
||||
// Build a shared SSRF-safe HTTP client for all downloads.
|
||||
httpClient := secutils.NewSSRFSafeHTTPClient(secutils.SSRFSafeHTTPClientConfig{
|
||||
Timeout: remoteImageFetchTimeout,
|
||||
MaxRedirects: 5,
|
||||
})
|
||||
// Two scans, each with its own budget. Sharing one would let HTML images eat
|
||||
// into the number of Markdown images a document already gets resolved today.
|
||||
markdown, mdImages := resolveRemoteImagePass(ctx, markdown, remotePassSpec{
|
||||
Pattern: imgMarkdownPattern,
|
||||
// Group 2 of imgMarkdownPattern is the target; group 1 is the alt text.
|
||||
URLGroup: 2,
|
||||
Syntax: "markdown",
|
||||
SrcOf: markdownSrc,
|
||||
}, client, fileSvc, tenantID)
|
||||
|
||||
processed := 0
|
||||
|
||||
// Process in reverse order so that earlier indices stay valid after replacements.
|
||||
for i := len(matches) - 1; i >= 0; i-- {
|
||||
if processed >= maxRemoteImages {
|
||||
break
|
||||
}
|
||||
m := matches[i]
|
||||
imgURL := markdown[m[4]:m[5]] // group 2: the URL
|
||||
|
||||
// Only process remote http(s) URLs.
|
||||
if !strings.HasPrefix(imgURL, "http://") && !strings.HasPrefix(imgURL, "https://") {
|
||||
continue
|
||||
}
|
||||
|
||||
// Already a provider scheme — skip.
|
||||
if isProviderScheme(imgURL) {
|
||||
continue
|
||||
}
|
||||
|
||||
// For whitelisted hosts: download to validate (mime type, icon check),
|
||||
// create StoredImage for downstream OCR/caption analysis, but do NOT
|
||||
// upload to storage and keep the original URL in markdown.
|
||||
// The multimodal service will download from the original URL later.
|
||||
whitelisted := isWhitelistedImageHost(imgURL)
|
||||
|
||||
// --- SSRF check (skip for whitelisted) ---
|
||||
if !whitelisted {
|
||||
if err := secutils.ValidateURLForSSRF(imgURL); err != nil {
|
||||
log.Printf("WARN: remote image blocked by SSRF check (%v): %s", err, imgURL)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// --- Download ---
|
||||
data, mimeType, dlErr := downloadImage(ctx, httpClient, imgURL)
|
||||
if dlErr != nil {
|
||||
log.Printf("WARN: failed to download remote image %s: %v", imgURL, dlErr)
|
||||
continue
|
||||
}
|
||||
|
||||
// Filter out icons / tiny decorative images.
|
||||
if isIconImage(data) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Determine file extension.
|
||||
ext := extFromMime(mimeType)
|
||||
if ext == "" {
|
||||
ext = extFromURLPath(imgURL)
|
||||
}
|
||||
if ext == "" {
|
||||
ext = ".png" // safe default
|
||||
}
|
||||
|
||||
var servingURL string
|
||||
if whitelisted {
|
||||
// Keep the original URL — ImageMultimodalService will download it
|
||||
// directly for OCR/caption analysis.
|
||||
servingURL = imgURL
|
||||
} else {
|
||||
// --- Upload to storage ---
|
||||
fileName := uuid.New().String() + ext
|
||||
var saveErr error
|
||||
servingURL, saveErr = fileSvc.SaveBytes(ctx, data, tenantID, fileName, false)
|
||||
if saveErr != nil {
|
||||
log.Printf("WARN: failed to save remote image %s: %v", imgURL, saveErr)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
images = append(images, StoredImage{
|
||||
OriginalRef: imgURL,
|
||||
ServingURL: servingURL,
|
||||
MimeType: mimeType,
|
||||
})
|
||||
|
||||
if !whitelisted {
|
||||
// Replace URL in markdown.
|
||||
markdown = markdown[:m[4]] + servingURL + markdown[m[5]:]
|
||||
}
|
||||
processed++
|
||||
}
|
||||
markdown, htmlImages := resolveRemoteImagePass(ctx, markdown, remotePassSpec{
|
||||
Pattern: imgHTMLSrc,
|
||||
URLGroup: searchutil.HTMLImageSrcURLGroup,
|
||||
Syntax: "html",
|
||||
SrcOf: htmlAttrSrc,
|
||||
}, client, fileSvc, tenantID)
|
||||
|
||||
images = append(images, mdImages...)
|
||||
images = append(images, htmlImages...)
|
||||
return markdown, images, nil
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -373,7 +373,7 @@ func extractImageRefsFromContent(content string) []string {
|
|||
refs = append(refs, strings.TrimSpace(match[2]))
|
||||
}
|
||||
}
|
||||
for _, match := range imgHTMLRelativeSrc.FindAllStringSubmatch(content, -1) {
|
||||
for _, match := range imgHTMLSrc.FindAllStringSubmatch(content, -1) {
|
||||
if len(match) >= 3 {
|
||||
refs = append(refs, match[2])
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,406 @@
|
|||
package docparser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
)
|
||||
|
||||
// remoteImageServer serves a valid PNG for every request and counts the hits so
|
||||
// that budget and dedup behaviour can be asserted directly.
|
||||
func remoteImageServer(t *testing.T) (*httptest.Server, *int64) {
|
||||
t.Helper()
|
||||
var hits int64
|
||||
png := createTestPNG(200, 200)
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
atomic.AddInt64(&hits, 1)
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(png)
|
||||
}))
|
||||
t.Cleanup(ts.Close)
|
||||
return ts, &hits
|
||||
}
|
||||
|
||||
func allowLocalhost(t *testing.T) {
|
||||
t.Helper()
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
|
||||
secutils.ResetSSRFWhitelistForTest()
|
||||
}
|
||||
|
||||
func resolve(t *testing.T, markdown string) (string, []StoredImage, *mockFileService) {
|
||||
t.Helper()
|
||||
fSvc := &mockFileService{}
|
||||
updated, images, err := NewImageResolver().ResolveRemoteImages(
|
||||
context.Background(), markdown, fSvc, 42)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
return updated, images, fSvc
|
||||
}
|
||||
|
||||
func TestResolveRemoteImages_HTMLTagRewritesSrcAndKeepsTag(t *testing.T) {
|
||||
allowLocalhost(t)
|
||||
ts, _ := remoteImageServer(t)
|
||||
|
||||
markdown := fmt.Sprintf(
|
||||
`<p><img class="screenshot" src="%s/a.png" alt="login screen" width="600"></p>`, ts.URL)
|
||||
|
||||
updated, images, _ := resolve(t, markdown)
|
||||
|
||||
if len(images) != 1 {
|
||||
t.Fatalf("expected 1 stored image, got %d", len(images))
|
||||
}
|
||||
if strings.Contains(updated, ts.URL) {
|
||||
t.Errorf("original URL still present: %s", updated)
|
||||
}
|
||||
if !strings.Contains(updated, images[0].ServingURL) {
|
||||
t.Errorf("serving URL missing from output: %s", updated)
|
||||
}
|
||||
// The surrounding markup is the reason these documents use HTML at all.
|
||||
for _, want := range []string{`<img`, `class="screenshot"`, `alt="login screen"`, `width="600"`, `</p>`} {
|
||||
if !strings.Contains(updated, want) {
|
||||
t.Errorf("tag structure lost, %q missing from: %s", want, updated)
|
||||
}
|
||||
}
|
||||
if strings.Contains(updated, "\n\n<img src=\"%s/html.png\">", ts.URL, ts.URL)
|
||||
|
||||
updated, images, _ := resolve(t, markdown)
|
||||
|
||||
if len(images) != 2 {
|
||||
t.Fatalf("expected 2 stored images, got %d", len(images))
|
||||
}
|
||||
if strings.Contains(updated, ts.URL) {
|
||||
t.Errorf("a remote URL survived: %s", updated)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveRemoteImages_IndependentBudgetPerSyntax(t *testing.T) {
|
||||
allowLocalhost(t)
|
||||
ts, _ := remoteImageServer(t)
|
||||
|
||||
// Adding HTML support must not reduce how many Markdown images a document
|
||||
// already gets resolved: each syntax carries its own budget.
|
||||
var b strings.Builder
|
||||
for i := 0; i < maxRemoteImages; i++ {
|
||||
fmt.Fprintf(&b, "\n\n", i, ts.URL, i)
|
||||
}
|
||||
for i := 0; i < 5; i++ {
|
||||
fmt.Fprintf(&b, "<img src=\"%s/html%d.png\">\n\n", ts.URL, i)
|
||||
}
|
||||
|
||||
updated, images, _ := resolve(t, b.String())
|
||||
|
||||
if len(images) != maxRemoteImages+5 {
|
||||
t.Fatalf("expected %d stored images, got %d", maxRemoteImages+5, len(images))
|
||||
}
|
||||
if strings.Contains(updated, ts.URL) {
|
||||
t.Errorf("a remote URL survived: %s", updated)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveRemoteImages_HTMLSrcNormalization(t *testing.T) {
|
||||
allowLocalhost(t)
|
||||
ts, _ := remoteImageServer(t)
|
||||
|
||||
t.Run("uppercase scheme", func(t *testing.T) {
|
||||
upper := strings.Replace(ts.URL, "http://", "HTTP://", 1)
|
||||
updated, images, _ := resolve(t, fmt.Sprintf(`<img SRC="%s/up.png">`, upper))
|
||||
if len(images) != 1 {
|
||||
t.Fatalf("expected uppercase scheme to be fetched, got %d", len(images))
|
||||
}
|
||||
// The scheme is normalized because every fetcher downstream compares it
|
||||
// byte-for-byte; an image counted as resolved but unfetchable is worse
|
||||
// than one left alone.
|
||||
if strings.Contains(images[0].OriginalRef, "HTTP://") {
|
||||
t.Errorf("scheme was not normalized: %q", images[0].OriginalRef)
|
||||
}
|
||||
if strings.Contains(updated, "HTTP://") {
|
||||
t.Errorf("document still carries the uppercase scheme: %s", updated)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("markdown uppercase scheme is left alone", func(t *testing.T) {
|
||||
// Markdown targets are handed through unchanged, so a document that
|
||||
// upstream leaves untouched stays untouched.
|
||||
upper := strings.Replace(ts.URL, "http://", "HTTP://", 1)
|
||||
markdown := fmt.Sprintf("", upper)
|
||||
updated, images, _ := resolve(t, markdown)
|
||||
if len(images) != 0 {
|
||||
t.Errorf("expected no markdown behaviour change, got %d image(s)", len(images))
|
||||
}
|
||||
if updated != markdown {
|
||||
t.Errorf("markdown content changed:\n got %q\nwant %q", updated, markdown)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("padded src", func(t *testing.T) {
|
||||
_, images, _ := resolve(t, fmt.Sprintf(`<img src=" %s/pad.png ">`, ts.URL))
|
||||
if len(images) != 1 {
|
||||
t.Fatalf("expected padded src to be fetched, got %d", len(images))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("entity encoded query", func(t *testing.T) {
|
||||
var got string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
got = r.URL.RawQuery
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
_, _ = w.Write(createTestPNG(200, 200))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
_, images, _ := resolve(t, fmt.Sprintf(`<img src="%s/q.png?a=1&b=2">`, srv.URL))
|
||||
if len(images) != 1 {
|
||||
t.Fatalf("expected 1 stored image, got %d", len(images))
|
||||
}
|
||||
if got != "a=1&b=2" {
|
||||
t.Errorf("entities were not decoded before the request: raw query %q", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestResolveRemoteImages_HTMLSrcFormsOutOfScope(t *testing.T) {
|
||||
allowLocalhost(t)
|
||||
ts, hits := remoteImageServer(t)
|
||||
|
||||
cases := map[string]string{
|
||||
"unquoted src": fmt.Sprintf(`<img src=%s/unquoted.png>`, ts.URL),
|
||||
"srcset only": fmt.Sprintf(`<img srcset="%s/set.png 2x">`, ts.URL),
|
||||
"relative src": `<img src="./images/local.png">`,
|
||||
"data uri src": `<img src="data:image/png;base64,AAAA">`,
|
||||
"provider src": `<img src="local://images/x.png">`,
|
||||
"non-img tag": fmt.Sprintf(`<video src="%s/v.mp4">`, ts.URL),
|
||||
}
|
||||
|
||||
for name, markdown := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
before := atomic.LoadInt64(hits)
|
||||
updated, images, _ := resolve(t, markdown)
|
||||
if len(images) != 0 {
|
||||
t.Errorf("expected no stored images, got %d", len(images))
|
||||
}
|
||||
if updated != markdown {
|
||||
t.Errorf("content changed:\n got %q\nwant %q", updated, markdown)
|
||||
}
|
||||
if got := atomic.LoadInt64(hits) - before; got != 0 {
|
||||
t.Errorf("expected no fetch, got %d", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveRemoteImages_HyphenatedAttributeIsNotSrc(t *testing.T) {
|
||||
allowLocalhost(t)
|
||||
ts, _ := remoteImageServer(t)
|
||||
|
||||
// A lazy-loading tag carries a placeholder in src and the real image in
|
||||
// data-src. Treating data-src as src would capture whichever came first and
|
||||
// leave the other unvisited, so only src counts.
|
||||
markdown := fmt.Sprintf(`<img data-src="/placeholder.svg" src="%s/real.png">`, ts.URL)
|
||||
|
||||
updated, images, _ := resolve(t, markdown)
|
||||
|
||||
if len(images) != 1 {
|
||||
t.Fatalf("expected the src image to be resolved, got %d", len(images))
|
||||
}
|
||||
if images[0].OriginalRef != ts.URL+"/real.png" {
|
||||
t.Errorf("expected src to be the fetched reference, got %s", images[0].OriginalRef)
|
||||
}
|
||||
if !strings.Contains(updated, `data-src="/placeholder.svg"`) {
|
||||
t.Errorf("data-src must be left alone: %s", updated)
|
||||
}
|
||||
if strings.Contains(updated, ts.URL) {
|
||||
t.Errorf("src was not rewritten: %s", updated)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveRemoteImages_HyphenatedAttributeOnlyIsNotResolved(t *testing.T) {
|
||||
allowLocalhost(t)
|
||||
ts, hits := remoteImageServer(t)
|
||||
|
||||
// The other half of the same trade-off, pinned deliberately. Requiring
|
||||
// whitespace before src means a tag carrying only a hyphenated *-src is no
|
||||
// longer treated as an image at all — the previous boundary did resolve it.
|
||||
// Recovering that needs an attribute parser rather than a regex; capturing a
|
||||
// lazy-loading placeholder while the real src goes unvisited is the worse of
|
||||
// the two failures.
|
||||
for _, attr := range []string{"data-src", "ng-src", "data-original-src"} {
|
||||
t.Run(attr, func(t *testing.T) {
|
||||
before := atomic.LoadInt64(hits)
|
||||
markdown := fmt.Sprintf(`<img %s="%s/only.png">`, attr, ts.URL)
|
||||
|
||||
updated, images, _ := resolve(t, markdown)
|
||||
|
||||
if len(images) != 0 {
|
||||
t.Errorf("expected no stored images, got %d", len(images))
|
||||
}
|
||||
if updated != markdown {
|
||||
t.Errorf("content changed:\n got %q\nwant %q", updated, markdown)
|
||||
}
|
||||
if got := atomic.LoadInt64(hits) - before; got != 0 {
|
||||
t.Errorf("expected no fetch, got %d", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveRemoteImages_WhitelistedHostAgreesWithDocument(t *testing.T) {
|
||||
var hits int64
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
atomic.AddInt64(&hits, 1)
|
||||
if got := r.URL.RawQuery; got != "a=1&b=2" {
|
||||
t.Errorf("expected entities decoded for the request, got raw query %q", got)
|
||||
}
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
_, _ = w.Write(createTestPNG(200, 200))
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
|
||||
t.Setenv("IMAGE_HOST_KEEP_URL", strings.TrimPrefix(ts.URL, "http://"))
|
||||
secutils.ResetSSRFWhitelistForTest()
|
||||
|
||||
markdown := fmt.Sprintf(`<img src=" %s/q.png?a=1&b=2 " alt="kept">`, ts.URL)
|
||||
|
||||
updated, images, fSvc := resolve(t, markdown)
|
||||
|
||||
if len(images) != 1 {
|
||||
t.Fatalf("expected 1 stored image, got %d", len(images))
|
||||
}
|
||||
if atomic.LoadInt64(&hits) != 1 {
|
||||
t.Fatalf("expected the image to be downloaded once, got %d", hits)
|
||||
}
|
||||
if len(fSvc.saved) != 0 {
|
||||
t.Errorf("a whitelisted image must not be uploaded, got %d uploads", len(fSvc.saved))
|
||||
}
|
||||
|
||||
serving := images[0].ServingURL
|
||||
// ServingURL carries two obligations that have to agree: later stages locate
|
||||
// the image by searching the document for it, and the multimodal stage fetches
|
||||
// that same string.
|
||||
if !strings.Contains(updated, serving) {
|
||||
t.Errorf("ServingURL %q is not present in the document %q", serving, updated)
|
||||
}
|
||||
if serving != ts.URL+"/q.png?a=1&b=2" {
|
||||
t.Errorf("ServingURL must be the normalized fetchable URL, got %q", serving)
|
||||
}
|
||||
if strings.TrimSpace(serving) != serving {
|
||||
t.Errorf("ServingURL must not carry padding: %q", serving)
|
||||
}
|
||||
if strings.Contains(serving, "&") {
|
||||
t.Errorf("ServingURL must not carry HTML entities: %q", serving)
|
||||
}
|
||||
if !strings.Contains(updated, `alt="kept"`) {
|
||||
t.Errorf("the rest of the tag must survive: %s", updated)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveRemoteImages_CodeExampleIsRewritten(t *testing.T) {
|
||||
allowLocalhost(t)
|
||||
ts, _ := remoteImageServer(t)
|
||||
|
||||
// Accepted limitation: this resolver does not parse Markdown structure, so a
|
||||
// tag shown as a documentation example inside a fence is rewritten like any
|
||||
// other. Recognising code spans reliably needs a Markdown parser; a
|
||||
// hand-rolled scanner risks the opposite and far worse failure of treating a
|
||||
// document's real screenshots as examples.
|
||||
markdown := fmt.Sprintf("```html\n<img src=\"%s/example.png\">\n```", ts.URL)
|
||||
|
||||
updated, images, _ := resolve(t, markdown)
|
||||
|
||||
if len(images) != 1 {
|
||||
t.Fatalf("expected the example to be resolved, got %d", len(images))
|
||||
}
|
||||
if strings.Contains(updated, ts.URL) {
|
||||
t.Errorf("expected the example to be rewritten: %s", updated)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveRemoteImages_CancelledContextStops(t *testing.T) {
|
||||
allowLocalhost(t)
|
||||
ts, hits := remoteImageServer(t)
|
||||
|
||||
var b strings.Builder
|
||||
for i := 0; i < 5; i++ {
|
||||
fmt.Fprintf(&b, "<img src=\"%s/c%d.png\">\n\n", ts.URL, i)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
_, images, err := NewImageResolver().ResolveRemoteImages(ctx, b.String(), &mockFileService{}, 42)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(images) != 0 {
|
||||
t.Errorf("expected no images after cancellation, got %d", len(images))
|
||||
}
|
||||
if got := atomic.LoadInt64(hits); got != 0 {
|
||||
t.Errorf("expected no fetch after cancellation, got %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveAndStoreThenResolveRemoteImages(t *testing.T) {
|
||||
allowLocalhost(t)
|
||||
ts, _ := remoteImageServer(t)
|
||||
|
||||
// Mirrors the real ingest order, where ResolveAndStore runs first and
|
||||
// ResolveRemoteImages then works on its output. This is the only place the
|
||||
// two HTML resolvers can interfere with each other.
|
||||
markdown := fmt.Sprintf(
|
||||
"<img src=\"images/relative.png\">\n\n<img src=\"%s/remote.png\">", ts.URL)
|
||||
|
||||
fSvc := &mockFileService{}
|
||||
resolver := NewImageResolver()
|
||||
|
||||
afterStore, storeImages, err := resolver.ResolveAndStore(context.Background(), &types.ReadResult{
|
||||
MarkdownContent: markdown,
|
||||
ImageRefs: []types.ImageRef{{
|
||||
OriginalRef: "images/relative.png",
|
||||
Filename: "relative.png",
|
||||
MimeType: "image/png",
|
||||
ImageData: createTestPNG(200, 200),
|
||||
}},
|
||||
}, fSvc, 42)
|
||||
if err != nil {
|
||||
t.Fatalf("ResolveAndStore: %v", err)
|
||||
}
|
||||
if len(storeImages) != 1 {
|
||||
t.Fatalf("expected the relative image stored, got %d", len(storeImages))
|
||||
}
|
||||
|
||||
afterRemote, remoteImages, err := resolver.ResolveRemoteImages(
|
||||
context.Background(), afterStore, fSvc, 42)
|
||||
if err != nil {
|
||||
t.Fatalf("ResolveRemoteImages: %v", err)
|
||||
}
|
||||
if len(remoteImages) != 1 {
|
||||
t.Fatalf("expected the remote image stored, got %d", len(remoteImages))
|
||||
}
|
||||
if strings.Contains(afterRemote, ts.URL) {
|
||||
t.Errorf("remote URL survived: %s", afterRemote)
|
||||
}
|
||||
if strings.Contains(afterRemote, "images/relative.png") {
|
||||
t.Errorf("relative reference was not rewritten by the earlier pass: %s", afterRemote)
|
||||
}
|
||||
if n := strings.Count(afterRemote, "<img"); n != 2 {
|
||||
t.Errorf("expected both tags preserved, found %d", n)
|
||||
}
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ import (
|
|||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
|
|
@ -14,6 +15,30 @@ import (
|
|||
// MarkdownImageRegex matches Markdown image links: 
|
||||
var MarkdownImageRegex = regexp.MustCompile(`!\[([^\]]*)\]\(([^)]+)\)`)
|
||||
|
||||
// HTMLImageSrcRegex matches an HTML <img> tag with a quoted src attribute.
|
||||
// Documents that rely on surrounding markup for layout embed their screenshots
|
||||
// this way, so image-derived text has to be matched back to these tags as well
|
||||
// as to Markdown image links.
|
||||
//
|
||||
// Submatches: 1 = attributes before src, 2 = the src value, 3 = attributes
|
||||
// after. Callers index the value through HTMLImageSrcURLGroup rather than
|
||||
// assuming a position.
|
||||
//
|
||||
// src must be preceded by whitespace so that data-src and other hyphenated
|
||||
// attribute names are not mistaken for it — matching those would capture a
|
||||
// lazy-loading placeholder and leave the real src unvisited. An unquoted src
|
||||
// and a srcset-only tag are deliberately out of scope; both are rare in
|
||||
// authored documents and matching them reliably needs an HTML parser.
|
||||
//
|
||||
// Both this package and the document parser share this one definition. Two
|
||||
// copies would be free to drift, and an image the parser stores but the
|
||||
// enricher cannot match back is exactly the kind of gap this exists to close.
|
||||
var HTMLImageSrcRegex = regexp.MustCompile(`(?i)<img\b([^>]*?)\ssrc\s*=\s*['"]([^'"]+)['"]([^>]*)>`)
|
||||
|
||||
// HTMLImageSrcURLGroup is the submatch index of the src value in
|
||||
// HTMLImageSrcRegex.
|
||||
const HTMLImageSrcURLGroup = 2
|
||||
|
||||
// CollectImageInfoByChunkIDs collects merged image_info JSON for each given
|
||||
// chunk ID by querying child chunks (image_ocr / image_caption). It supports
|
||||
// two-level resolution:
|
||||
|
|
@ -288,22 +313,52 @@ func EnrichContentWithImageInfoForChat(content string, imageInfoJSON string) str
|
|||
}
|
||||
}
|
||||
|
||||
content = MarkdownImageRegex.ReplaceAllStringFunc(content, func(markdownImage string) string {
|
||||
match := MarkdownImageRegex.FindStringSubmatch(markdownImage)
|
||||
if len(match) < 3 {
|
||||
return markdownImage
|
||||
// Screenshots embedded as HTML carry their image_info the same way as
|
||||
// Markdown links: without covering both, a document that keeps its images in
|
||||
// <img> tags reaches the model as bare markup with the caption and OCR text
|
||||
// stripped out, even though the analysis ran and the entry is right here.
|
||||
//
|
||||
// Both syntaxes are located against the ORIGINAL content and spliced in one
|
||||
// right-to-left pass. Running one regex over the other's output would let a
|
||||
// metadata block that itself quotes an image reference be rescanned, cutting
|
||||
// the OCR sentence in half and injecting the same block twice.
|
||||
type injection struct {
|
||||
at int
|
||||
text string
|
||||
}
|
||||
var injections []injection
|
||||
|
||||
// trim is applied to HTML only. An attribute value may be padded, while a
|
||||
// Markdown target is looked up exactly as written so that the keys this
|
||||
// function matches on stay the ones it has always matched on.
|
||||
appendFor := func(locs [][]int, urlGroup int, trim bool) {
|
||||
for _, loc := range locs {
|
||||
start, end := loc[2*urlGroup], loc[2*urlGroup+1]
|
||||
if start < 0 {
|
||||
continue
|
||||
}
|
||||
key := content[start:end]
|
||||
if trim {
|
||||
key = strings.TrimSpace(key)
|
||||
}
|
||||
imgInfo, found := imageInfoMap[key]
|
||||
if !found || imgInfo == nil {
|
||||
continue
|
||||
}
|
||||
metadata := buildImageInfoMarkdownMetadata(imgInfo)
|
||||
if metadata == "" {
|
||||
continue
|
||||
}
|
||||
injections = append(injections, injection{at: loc[1], text: "\n\n" + metadata})
|
||||
}
|
||||
imgURL := match[2]
|
||||
imgInfo, found := imageInfoMap[imgURL]
|
||||
if !found || imgInfo == nil {
|
||||
return markdownImage
|
||||
}
|
||||
metadata := buildImageInfoMarkdownMetadata(imgInfo)
|
||||
if metadata == "" {
|
||||
return markdownImage
|
||||
}
|
||||
return markdownImage + "\n\n" + metadata
|
||||
})
|
||||
}
|
||||
appendFor(MarkdownImageRegex.FindAllStringSubmatchIndex(content, -1), 2, false)
|
||||
appendFor(HTMLImageSrcRegex.FindAllStringSubmatchIndex(content, -1), HTMLImageSrcURLGroup, true)
|
||||
|
||||
sort.Slice(injections, func(i, j int) bool { return injections[i].at > injections[j].at })
|
||||
for _, inj := range injections {
|
||||
content = content[:inj.at] + inj.text + content[inj.at:]
|
||||
}
|
||||
return content
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,193 @@
|
|||
package searchutil
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
func imageInfoJSON(t *testing.T, infos ...types.ImageInfo) string {
|
||||
t.Helper()
|
||||
data, err := json.Marshal(infos)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal image info: %v", err)
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func TestImageURLsInContent_CollectsHTMLSrc(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
content string
|
||||
want string
|
||||
}{
|
||||
{"markdown", "", "local://images/a.png"},
|
||||
{"html double quotes", `<img src="local://images/b.png">`, "local://images/b.png"},
|
||||
{"html single quotes", `<img src='local://images/c.png'>`, "local://images/c.png"},
|
||||
{"html with attributes", `<img class="x" src="local://images/d.png" alt="y">`, "local://images/d.png"},
|
||||
{"html uppercase", `<IMG SRC="local://images/e.png">`, "local://images/e.png"},
|
||||
{"html padded", `<img src=" local://images/f.png ">`, "local://images/f.png"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
urls := ImageURLsInContent(tc.content)
|
||||
if !urls[tc.want] {
|
||||
t.Errorf("expected %q to be collected from %q, got %v", tc.want, tc.content, urls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterImageInfoByContentURLs_KeepsHTMLReferencedEntry(t *testing.T) {
|
||||
info := types.ImageInfo{
|
||||
URL: "local://images/shot.png",
|
||||
Caption: "the login screen",
|
||||
OCRText: "Sign in with SSO",
|
||||
}
|
||||
|
||||
// A passage whose images are HTML tags used to look image-free, which made
|
||||
// the filter drop every entry it was given.
|
||||
got := FilterImageInfoByContentURLs(
|
||||
`<p><img src="local://images/shot.png" alt="login"></p>`,
|
||||
imageInfoJSON(t, info),
|
||||
)
|
||||
if got == "" {
|
||||
t.Fatal("expected the entry to be kept for an HTML-only passage")
|
||||
}
|
||||
|
||||
var kept []types.ImageInfo
|
||||
if err := json.Unmarshal([]byte(got), &kept); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if len(kept) != 1 || kept[0].URL != info.URL {
|
||||
t.Errorf("unexpected filter result: %+v", kept)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterImageInfoByContentURLs_StillDropsUnreferenced(t *testing.T) {
|
||||
got := FilterImageInfoByContentURLs(
|
||||
`<p><img src="local://images/present.png"></p>`,
|
||||
imageInfoJSON(t, types.ImageInfo{URL: "local://images/absent.png", OCRText: "elsewhere"}),
|
||||
)
|
||||
if got != "" {
|
||||
t.Errorf("expected an unreferenced entry to be dropped, got %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnrichContentWithImageInfoForChat_HTMLTag(t *testing.T) {
|
||||
info := types.ImageInfo{
|
||||
URL: "local://images/shot.png",
|
||||
Caption: "the login screen",
|
||||
OCRText: "Sign in with SSO",
|
||||
}
|
||||
content := `<p><img src="local://images/shot.png" alt="login"></p>`
|
||||
|
||||
got := EnrichContentWithImageInfoForChat(content, imageInfoJSON(t, info))
|
||||
|
||||
if !strings.Contains(got, "Sign in with SSO") {
|
||||
t.Errorf("OCR text was not injected for an HTML image: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "the login screen") {
|
||||
t.Errorf("caption was not injected for an HTML image: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, `<img src="local://images/shot.png"`) {
|
||||
t.Errorf("the original tag should be preserved: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnrichContentWithImageInfoForChat_MarkdownUnchanged(t *testing.T) {
|
||||
info := types.ImageInfo{
|
||||
URL: "local://images/shot.png",
|
||||
OCRText: "Sign in with SSO",
|
||||
}
|
||||
content := ""
|
||||
|
||||
got := EnrichContentWithImageInfoForChat(content, imageInfoJSON(t, info))
|
||||
|
||||
if !strings.Contains(got, "") {
|
||||
t.Errorf("markdown image should be preserved: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "Sign in with SSO") {
|
||||
t.Errorf("markdown enrichment regressed: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterImageInfoByMatchRange_HTMLTagInsideWindow(t *testing.T) {
|
||||
info := types.ImageInfo{URL: "local://images/shot.png", OCRText: "Sign in with SSO"}
|
||||
parent := `intro text
|
||||
<img src="local://images/shot.png">
|
||||
tail text`
|
||||
|
||||
// Window covering the tag: the entry survives.
|
||||
got := FilterImageInfoByMatchRange(parent, 0, 0, len([]rune(parent)), imageInfoJSON(t, info))
|
||||
if got == "" {
|
||||
t.Error("expected the entry to survive a window containing the whole tag")
|
||||
}
|
||||
|
||||
// Window that cuts the tag in half: nothing matches, which is the known
|
||||
// limitation — an HTML tag is several times longer than  and
|
||||
// straddles a child window far more often.
|
||||
if got := FilterImageInfoByMatchRange(parent, 0, 0, 20, imageInfoJSON(t, info)); got != "" {
|
||||
t.Errorf("expected a truncated tag not to match, got %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnrichContentWithImageInfoForChat_DoesNotRescanInjectedMetadata(t *testing.T) {
|
||||
// The OCR text of a screenshot that documents an <img> tag contains one.
|
||||
// Scanning the injected metadata would splice a second block into the middle
|
||||
// of the first.
|
||||
info := types.ImageInfo{
|
||||
URL: "local://images/x.png",
|
||||
OCRText: `use <img src="local://images/x.png"> to embed`,
|
||||
}
|
||||
content := ""
|
||||
|
||||
got := EnrichContentWithImageInfoForChat(content, imageInfoJSON(t, info))
|
||||
|
||||
if n := strings.Count(got, "**Image text (OCR):**"); n != 1 {
|
||||
t.Errorf("expected exactly 1 metadata block, got %d:\n%s", n, got)
|
||||
}
|
||||
if !strings.Contains(got, "to embed") {
|
||||
t.Errorf("OCR sentence was truncated:\n%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnrichContentWithImageInfoForChat_BothSyntaxesOneBlockEach(t *testing.T) {
|
||||
info := types.ImageInfo{URL: "local://images/x.png", Caption: "shot"}
|
||||
content := "\n\n<img src=\"local://images/x.png\">"
|
||||
|
||||
got := EnrichContentWithImageInfoForChat(content, imageInfoJSON(t, info))
|
||||
|
||||
if n := strings.Count(got, "**Image caption:** shot"); n != 2 {
|
||||
t.Errorf("expected one block per reference (2), got %d:\n%s", n, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTMLImageSrcRegex_HyphenatedAttributeIsNotSrc(t *testing.T) {
|
||||
urls := ImageURLsInContent(`<img data-src="local://images/placeholder.png" src="local://images/real.png">`)
|
||||
if urls["local://images/placeholder.png"] {
|
||||
t.Error("data-src must not be collected as src")
|
||||
}
|
||||
if !urls["local://images/real.png"] {
|
||||
t.Errorf("src was not collected: %v", urls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnrichContentWithImageInfoForChat_UnmatchedImageStaysBare(t *testing.T) {
|
||||
// The chat variant deliberately enriches only images that appear in the
|
||||
// passage, so an entry for some other page must not be appended.
|
||||
info := types.ImageInfo{URL: "local://images/other.png", OCRText: "another page"}
|
||||
content := `<p><img src="local://images/shot.png"></p>`
|
||||
|
||||
got := EnrichContentWithImageInfoForChat(content, imageInfoJSON(t, info))
|
||||
|
||||
if got != content {
|
||||
t.Errorf("expected content untouched, got %s", got)
|
||||
}
|
||||
if strings.Contains(got, "another page") {
|
||||
t.Errorf("an orphan entry leaked into the passage: %s", got)
|
||||
}
|
||||
}
|
||||
|
|
@ -30,8 +30,8 @@ func SliceContentByDocumentRange(content string, contentStartAt, rangeStart, ran
|
|||
return string(runes[relStart:relEnd])
|
||||
}
|
||||
|
||||
// ImageURLsInContent returns the set of image URLs referenced as Markdown
|
||||
// images in content.
|
||||
// ImageURLsInContent returns the set of image URLs referenced by content,
|
||||
// covering both Markdown image links and HTML <img> tags with a quoted src.
|
||||
func ImageURLsInContent(content string) map[string]bool {
|
||||
urls := make(map[string]bool)
|
||||
for _, match := range MarkdownImageRegex.FindAllStringSubmatch(content, -1) {
|
||||
|
|
@ -40,12 +40,24 @@ func ImageURLsInContent(content string) map[string]bool {
|
|||
}
|
||||
urls[match[2]] = true
|
||||
}
|
||||
// Screenshots embedded as HTML count as present in the content too.
|
||||
// Collecting only Markdown links would make the image_info filters treat an
|
||||
// HTML-only passage as holding no images at all and drop every entry.
|
||||
for _, match := range HTMLImageSrcRegex.FindAllStringSubmatch(content, -1) {
|
||||
if len(match) <= HTMLImageSrcURLGroup {
|
||||
continue
|
||||
}
|
||||
if src := strings.TrimSpace(match[HTMLImageSrcURLGroup]); src != "" {
|
||||
urls[src] = true
|
||||
}
|
||||
}
|
||||
return urls
|
||||
}
|
||||
|
||||
// FilterImageInfoByContentURLs keeps only image_info entries whose URL or
|
||||
// OriginalURL appears as a Markdown image in content. Returns empty string
|
||||
// when nothing matches or imageInfoJSON is invalid.
|
||||
// OriginalURL is referenced by content, as either a Markdown image link or an
|
||||
// HTML <img> tag. Returns empty string when nothing matches or imageInfoJSON
|
||||
// is invalid.
|
||||
func FilterImageInfoByContentURLs(content string, imageInfoJSON string) string {
|
||||
if imageInfoJSON == "" {
|
||||
return ""
|
||||
|
|
@ -117,8 +129,8 @@ func PruneMarkdownImagesByImageInfo(content, imageInfoJSON string) string {
|
|||
return collapseBlankLines(filtered)
|
||||
}
|
||||
|
||||
// FilterImageInfoByMatchRange keeps image_info entries whose Markdown image
|
||||
// reference falls within the document rune range [matchStart, matchEnd).
|
||||
// FilterImageInfoByMatchRange keeps image_info entries whose image reference
|
||||
// falls within the document rune range [matchStart, matchEnd).
|
||||
// Used when parent content is expanded for context but multimodal enrichment
|
||||
// should only cover the retrieved child window.
|
||||
func FilterImageInfoByMatchRange(
|
||||
|
|
|
|||
Loading…
Reference in New Issue